[英]Python: List get the same items
我有3个清单。
我需要结果是相同的项目。
def main(args):
list1 = ["hello", "day", "apple", "hi", "word"];
list2 = ["food", "hi", "world", "hello", "python"];
list3 = ["hi", "hello", "april", "text", "morning"];
#result must be ["hi", "hello"]
return 0;
我该怎么做?
尝试使用python设置交集方法
list1 = ["hello", "day", "apple", "hi", "word"]
list2 = ["food", "hi", "world", "hello", "python"]
list3 = ["hi", "hello", "april", "text", "morning"]
set1 = set(list1)
set2 = set(list2)
set3 = set(list3)
print(set1.intersection(set2).intersection(set3))
输出:
{'hello', 'hi'}
或者,您也可以将列表声明为已设置。
set1 = {"hello", "day", "apple", "hi", "word"}
set2 = {"food", "hi", "world", "hello", "python"}
set3 = {"hi", "hello", "april", "text", "morning"}
print(set1.intersection(set2).intersection(set3))
在这种情况下,所有重复项将从set1,set2和set3中删除
如果您不想使用set()
,则可以使用列表推导:
list1 = ["hello", "day", "apple", "hi", "word"]
list2 = ["food", "hi", "world", "hello", "python"]
list3 = ["hi", "hello", "april", "text", "morning"]
print(list(i for i in (i for i in list1 if i in list2) if i in list3))
印刷品:
['hello', 'hi']
使用集合和&
运算符查找交集:
same_words = set(list1) & set(list2) & set(list3)
如果需要返回列表,只需将集合转换回列表数据类型即可。
return list(same_words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.