如何在Python中查找属于另一个列表中另一个元素的列表中的元素

2024-05-08 22:58:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个清单:

dc = ["hello", "world"]

还有这个:

^{pr2}$

我希望在dc上找到那些元素,它们是任何线元素的一部分。。。在

我可以将线路循环为:

for line in lines:
    # what to do here?

但我不知道如何准确地找到dc中的“hello”元素在lines的“anexample of hello”元素中,或者在dc中的“world”在line中的“line in the world of strings”中。。。在

也许我不该绕线?在


Tags: oftoin元素helloforworldhere
2条回答

使用set特征的一次线性解

首先从你的台词中找出所有的单词。将它们作为一个集合,以节省空间并获得一些有用的功能(请参见下文)。然后在上面使用&操作,并从您要查找的单词创建集。解决方案可以是一行:

>>> set(dc) & set(sum(map(str.split, lines), []))
set(['world', 'hello'])

如果您希望结果是一个列表,只需将其转换为如下列表:

^{pr2}$
>>> dc = ["hello", "world", "foo"]
>>> lines = ["This is", "an example of hello", "line in the world of strings", "Testing"]
>>> [word for word in dc if any(word in line for line in lines)]
['hello', 'world']

相关问题 更多 >