gpt4 book ai didi

python - 2个列表之间的共同元素比较

转载 作者:IT老高 更新时间:2023-10-28 21:07:24 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']
"""
for element in list1:
if element in list2:
return list(element)

到目前为止,但似乎无法让它发挥作用!

有什么想法吗?

最佳答案

使用 Python 的 set intersection :

>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]

关于python - 2个列表之间的共同元素比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2864842/

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