2个列表的公共元素比较 [英] Common elements comparison between 2 lists
本文介绍了2个列表的公共元素比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def common_elements(list1, list2):"""返回包含 list1 和 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'])['这个那个']"""对于 list1 中的元素:如果列表 2 中的元素:返回列表(元素)
到此为止,但似乎无法让它工作!
有什么想法吗?
解决方案
使用 Python 的 设置交集:
<预><代码>>>>list1 = [1,2,3,4,5,6]>>>列表 2 = [3, 5, 7, 9]>>>列表(设置(列表1).交叉点(列表2))[3, 5]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)
Got that so far, but can't seem to get it to work!
Any ideas?
解决方案
Use Python's set intersection:
>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
这篇关于2个列表的公共元素比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文