简体   繁体   English

比较2个列表中元素的有效方法

[英]Efficient way to compare elements in 2 lists

I want to compare entries in 2 lists: 我想比较2个列表中的条目:

for example: 例如:

for key in keys:
        for elem in elements:
            #Find a key in common with 2 lists and write the corresponding value
            if key == elem:
                 do something
            #Iterate through elements unit the current "key" value is found.
            else:
                 pass

Problem with this method is that it is very slow, is there a faster way to do this? 这种方法的问题在于它非常慢,有没有更快的方法呢?

*Assuming len(keys) > len(elements) *假设len(keys) > len(elements)

Use sets, and then set intersection will return the common elements. 使用集合,然后集合相交将返回公共元素。

Set intersection is an O(min(len(s1), len(s2)) operation. 设置交集是O(min(len(s1), len(s2))操作。

>>> s1 = range(10)
>>> s2 = range(5,20)
>>> set(s1) & set(s2)  #set intersection returns the common keys
set([8, 9, 5, 6, 7])   # order not preserved 

Turn them into sets: 将它们变成集合:

set1 = set(keys)
set2 = set(elements)

And now you can find their intersection: 现在您可以找到他们的交集:

set1.intersection(set2)

The sets won't preserve order, so you'll get back just the common elements. 这些集合不会保留顺序,因此您将只获得常见元素。

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

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