[英]How to select elements in the intersection of two lists in Python
作為一個簡單的例子:
list1 = ['a', 'b', 'c']
list2 = ['a', 'stack', 'overflow']
for i in list1 and list2:
print i
這將打印list2
所有元素。 為什么是這樣? 我怎樣才能打印兩個列表中的元素?
如果您的列表可能很大,最好將它們轉換為集合並使用它們的交集:
list1 = ['a', 'b', 'c']
list2 = ['a', 'stack', 'overflow']
for i in set(list1).intersection(set(list2)):
print i
如果您想重復迭代該交集,請將其保存在自己的變量中( intersect = set(list1).intersection(set(list2))
)。
你也可以使用:
for i in list 1:
if i in list2:
print i
但是在列表中使用in
來檢查成員資格的問題在於它可以是O(n)
操作,因此總的來說,你的循環變為O(n ^ 2)。 OTOH, in
成員set
上使用是O(1),所以它更快。
至於你的原始問題,當你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.