简体   繁体   English

在两个python列表中查找常见项目的索引

[英]Find indexes of common items in two python lists

I have two lists in python list_A and list_B and I want to find the common item they share. 我在python list_A和list_B中有两个列表,我想找到它们共享的共同项目。 My code to do so is the following: 我的代码如下:

both = []
for i in list_A:
    for j in list_B:
        if i == j:
            both.append(i)

The list common in the end contains the common items. 最后的公用列表包含公用项目。 However, I want also to return the indexes of those elements in the initial two lists. 但是,我还想返回最初两个列表中这些元素的索引。 How can I do so? 我该怎么办?

It is advised in python that you avoid as much as possible to use for loops. 它在您避免尽可能多地使用Python建议for循环。 You can efficiently find the common elements in the two lists by using python set as follows 您可以通过如下所示的python set高效地找到两个列表中的公共元素

both = set(list_A).intersection(list_B)

Then you can find the indices using the build-in index method 然后,您可以使用内置index方法找到index

indices_A = [list_A.index(x) for x in both]
indices_B = [list_B.index(x) for x in both]

Instead of iterating through the list, access elements by index: 不用遍历列表,而是按索引访问元素:

both = []
for i in range(len(list_A)):
    for j in range(len(list_B)):
        if list_A[i] == list_B[j]:
            both.append((i,j))

Here i and j will take integer values and you can check values in list_A and list_B by index. 在这里,i和j将取整数值,您可以按索引检查list_A和list_B中的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM