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

Python 比较两个列表中元素的有效方法,python,Python,我想比较两个列表中的条目: 例如: 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

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

例如:

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(键)>len(元素)

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

设置交叉点是一个
O(最小值(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 

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

设置交叉点是一个
O(最小值(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 
把它们分成几组:

set1 = set(keys)
set2 = set(elements)
现在您可以找到它们的交叉点:

set1.intersection(set2)
这些集合不会保持顺序,因此您只能返回常用元素。

将它们转换为集合:

set1 = set(keys)
set2 = set(elements)
现在您可以找到它们的交叉点:

set1.intersection(set2)

集合不会保留顺序,因此您只能返回普通元素。

请注意,
set.intersection
可以接受一个iterable,因此严格来说,不需要将元素转换为
set2
。请注意,
set.intersection
可以接受一个iterable,以便将元素转换为
set2
绝对不需要。