def common_elements(list1, list2):
"""
Return a list containing the elements which are in both list1 and list2
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>> common_elements(["this","this","n","that"],["this","not","that","that"])
['this', 'that']
"""
result = []
for element in list1:
if element in list2:
result.append(element)
return result
到目前为止我有这个,但它返回重复项,例如:
common_elements(["this","this","n","that"],["this","not","that","that"])
返回为:['this', 'this', 'that']
答案 0 :(得分:6)
使用set.intersection()
,因为这意味着无需将list2
转换为集合
def common_elements(list1, list2):
return set(list1).intersection(list2)
选择较短的列表转换为集合
更有效def common_elements(list1, list2):
short_list, long_list = sorted((list1, list2), key=len)
return set(short_list).intersection(long_list)
当然要返回一个列表,你会使用
return list(set(...))
答案 1 :(得分:4)
使用sets:
>>> a, b = [1,2,3,4,5,6], [3,5,7,9]
>>> set(a).intersection(b)
set([3, 5])
答案 2 :(得分:3)
def common_elements(a, b):
return list(set(a) & set(b))
在这种情况下,我们采用两个集合的交集,这两个集合又由两个列表构成。每组由每个列表中的唯一项组成。我们最终转换回列表,因为这是所需的返回类型。
答案 3 :(得分:1)
>>> a = [1,2,3,4,5,6]
>>> b = [3,5,7,9]
>>> list(set(a).intersection(b))
[3, 5]
编辑:不需要将b转换为集合。谢谢@Johnsyweb
答案 4 :(得分:0)
你想使用集合,因为它们有一些非常好的操作:
>>> a = set([1, 2, 3, 4])
>>> b = set([3, 4, 5, 6])
>>> a.intersection(b)
set([3, 4])
>>> a.difference(b)
set([1, 2])
>>> b.intersection(a)
set([5, 6])
>>> a.union(b)
set([1, 2, 3, 4, 5, 6])