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
Run Code Online (Sandbox Code Playgroud)
到目前为止我有这个,但它返回重复项,例如:
common_elements(["this","this","n","that"],["this","not","that","that"])
Run Code Online (Sandbox Code Playgroud)
返回为: ['this', 'this', 'that']
使用set.intersection()因为它意味着没有必要转换list2为集合
def common_elements(list1, list2):
return set(list1).intersection(list2)
Run Code Online (Sandbox Code Playgroud)
选择较短的列表转换为集合更有效
def common_elements(list1, list2):
short_list, long_list = sorted((list1, list2), key=len)
return set(short_list).intersection(long_list)
Run Code Online (Sandbox Code Playgroud)
当然要返回一个列表,你会用
return list(set(...))
Run Code Online (Sandbox Code Playgroud)
>>> a = [1,2,3,4,5,6]
>>> b = [3,5,7,9]
>>> list(set(a).intersection(b))
[3, 5]
Run Code Online (Sandbox Code Playgroud)
编辑:不需要将 b 转换为集合。谢谢@Johnsyweb