简体   繁体   English

如何在Python中的两个列表的交集中选择元素

[英]How to select elements in the intersection of two lists in Python

As a quick example: 作为一个简单的例子:

list1 = ['a', 'b', 'c']
list2 = ['a', 'stack', 'overflow']
for i in list1 and list2:
    print i

this prints all the elements in list2 . 这将打印list2所有元素。 Why is this? 为什么是这样? How can I just print the elements that are in both lists? 我怎样才能打印两个列表中的元素?

If your lists can be big, its better to convert them to sets and use intersection over them: 如果您的列表可能很大,最好将它们转换为集合并使用它们的交集:

list1 = ['a', 'b', 'c']
list2 = ['a', 'stack', 'overflow']

for i in set(list1).intersection(set(list2)):
    print i

In case you want to iterate on that intersection repetitively, save it in a variable of its own ( intersect = set(list1).intersection(set(list2)) ). 如果您想重复迭代该交集,请将其保存在自己的变量中( intersect = set(list1).intersection(set(list2)) )。

You could also use: 你也可以使用:

for i in list 1:
    if i in list2:
        print i

but the problem of using in in a list for checking membership is that it can be an O(n) operation, so overall, your loop becomes O(n^2). 但是在列表中使用in来检查成员资格的问题在于它可以是O(n)操作,因此总的来说,你的循环变为O(n ^ 2)。 OTOH, using in on a set for membership is O(1), so it is much faster. OTOH, in成员set上使用是O(1),所以它更快。

As for your original question, when you do for i in list1 and list2 , it is interpreted as for i in (list1 and list2) , and the value of list1 and list2 is simply list2 if list1 is not empty, so you end up iterating over the second list only. 至于你的原始问题,当你for i in list1 and list2做时,它被解释for i in (list1 and list2) ,如果list1不为空,则list1 list1 and list2值只是list2,所以你最终迭代仅在第二个列表上。

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

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