📜  从其他元组列表中查找元组索引的Python程序

📅  最后修改于: 2022-05-13 01:55:08.079000             🧑  作者: Mango

从其他元组列表中查找元组索引的Python程序

给定元组列表和由要搜索的元组组成的搜索列表,我们的任务是编写一个Python程序来提取匹配元组的索引。

方法 #1:使用查找字典+ enumerate() +列表推导

在这种情况下,形成了一个查找字典来映射所有具有匹配索引的元组。然后使用查找字典来获取映射元组的索引作为使用列表理解的结果。

Python3
# Python3 code to demonstrate working of
# Find tuple indices from other tuple list
# Using lookup dictionary + enumerate() + list comprehension
  
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search tuple 
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
  
# creating lookup_dict
lookup_dict = {val: key for key,val in enumerate(test_list)}
  
# creating result list
res = [lookup_dict[idx] for idx in search_tup if idx in lookup_dict]
  
# printing result
print("The match tuple indices : " + str(res))


Python3
# Python3 code to demonstrate working of
# Find tuple indices from other tuple list
# Using list comprehension + enumerate()
  
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search tuple 
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
  
# enumerate() gets all the indices 
res = [idx for idx, val in enumerate(test_list) for ele in search_tup if ele == val]
  
# printing result
print("The match tuple indices : " + str(res))


输出:

The original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The match tuple indices : [3, 1]

方法 #2:使用列表理解 + enumerate()

在这里,我们使用 enumerate() 执行获取索引的任务,列表推导用于元组所有元素的迭代和相等匹配的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Find tuple indices from other tuple list
# Using list comprehension + enumerate()
  
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search tuple 
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
  
# enumerate() gets all the indices 
res = [idx for idx, val in enumerate(test_list) for ele in search_tup if ele == val]
  
# printing result
print("The match tuple indices : " + str(res))

输出:

The original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The match tuple indices : [1, 3]