gpt4 book ai didi

python - 如何返回包含公共(public)元素且不重复的列表

转载 作者:太空狗 更新时间:2023-10-30 00:28:42 24 4
gpt4 key购买 nike

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']

最佳答案

使用 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(...))

关于python - 如何返回包含公共(public)元素且不重复的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6039009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com