Python:List获取相同的项

Python:List获取相同的项,python,Python,我有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

我有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\u words=set(列表1)&set(列表2)&set(列表3)

如果需要返回列表,只需将集合强制转换回列表数据类型即可


返回列表(相同的单词)

您自己尝试过解决这个问题吗?您使用了什么代码?您遇到了什么问题?我使用了
[i for i in list1 if i in list2]
,但这只有两个列表。非常感谢,这是我需要的。或者只是
列表(set(list1)&set(list2)&set(list3))