繁体   English   中英

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

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

我在python list_A和list_B中有两个列表,我想找到它们共享的共同项目。 我的代码如下:

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

最后的公用列表包含公用项目。 但是,我还想返回最初两个列表中这些元素的索引。 我该怎么办?

它在您避免尽可能多地使用Python建议for循环。 您可以通过如下所示的python set高效地找到两个列表中的公共元素

both = set(list_A).intersection(list_B)

然后,您可以使用内置index方法找到index

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

不用遍历列表,而是按索引访问元素:

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))

在这里,i和j将取整数值,您可以按索引检查list_A和list_B中的值。

暂无
暂无

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

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