2

我想比较 2 个列表中的条目:

例如:

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

这种方法的问题是它非常慢,有没有更快的方法来做到这一点?

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

4

2 回答 2

3

使用集合,然后集合交集将返回公共元素。

设置交集是一个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 
于 2013-06-07T01:23:57.187 回答
1

把它们变成集合:

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

现在你可以找到它们的交集:

set1.intersection(set2)

这些集合不会保留顺序,因此您将仅返回公共元素。

于 2013-06-07T01:24:19.297 回答