如何返回不包含重复项的公共元素列表
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']
5 个回答
4
使用集合:
>>> a, b = [1,2,3,4,5,6], [3,5,7,9]
>>> set(a).intersection(b)
set([3, 5])
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
>>> a = [1,2,3,4,5,6]
>>> b = [3,5,7,9]
>>> list(set(a).intersection(b))
[3, 5]
编辑: 不需要把 b 转换成集合。谢谢 @Johnsyweb