📌  相关文章
📜  Python程序获取另一个列表中一个列表的每个元素的索引

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

Python程序获取另一个列表中一个列表的每个元素的索引

给定 2 个列表,从 list1 中获取 list2 中每个元素的所有出现的所有索引。

方法 #1:使用循环 + setdefault()

在此,我们执行将所有元素列表与其索引分组的任务,并在第二次运行中,仅获取存在于另一个列表中的元素。

Python3
# Python3 code to demonstrate working of 
# Multiple Indices from list elements
# Using setdefault() + loop
  
# initializing list
test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing get_list 
get_list = [7, 5, 3]
  
# getting all elements indices
ele_indices = dict()  
for idx, val in enumerate(test_list):
    ele_indices.setdefault(val, []).append(idx)
  
# filtering only required elements
res = [ele_indices.get(idx, [None]) for idx in get_list]   
  
# printing result 
print("Filtered Indices of elements in list 1  : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Multiple Indices from list elements
# Using list comprehension + enumerate()
  
# initializing list
test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing get_list 
get_list = [7, 5, 3]
  
# enumerate() used to get idx, val simultaneously
res = [([idx for idx, val in enumerate(test_list) if val == sub] if sub in test_list else [None])
      for sub in get_list]
  
# printing result 
print("Indices of elements in list 1  : " + str(res))


输出
The original list is : [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
Filtered Indices of elements in list 1  : [[3], [1, 9], [2, 5, 8, 11]]

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

在这里,我们使用嵌套循环来获取所有索引,然后在另一个列表中存在的情况下进行过滤。

蟒蛇3

# Python3 code to demonstrate working of 
# Multiple Indices from list elements
# Using list comprehension + enumerate()
  
# initializing list
test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing get_list 
get_list = [7, 5, 3]
  
# enumerate() used to get idx, val simultaneously
res = [([idx for idx, val in enumerate(test_list) if val == sub] if sub in test_list else [None])
      for sub in get_list]
  
# printing result 
print("Indices of elements in list 1  : " + str(res))
输出
The original list is : [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3]
Indices of elements in list 1  : [[3], [1, 9], [2, 5, 8, 11]]