如何在列表中查找元素,该元素是Python中另一个列表中另一个元素的一部分

Jav*_* C. 1 python list find

我有这个清单:

dc = ["hello", "world"]
Run Code Online (Sandbox Code Playgroud)

而另一个:

lines = ["This is", "an example of hello", "line in the world of strings", "Testing"]
Run Code Online (Sandbox Code Playgroud)

我希望在直流上找到那些属于线条任何元素的元素......

我可以将行循环为:

for line in lines:
    # what to do here?
Run Code Online (Sandbox Code Playgroud)

但我不知道如何确切地找到dc中的"hello"元素可以在"hello的例子"中找到,或者在"字符串世界中的行"中找到dc中的"world"在线......

也许我不应该循环线?

Rei*_*ica 6

>>> 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']
Run Code Online (Sandbox Code Playgroud)

  • 请注意,部分单词可能会匹配.`in`操作符仍然是一个很好的选择imo,但解决方案需要更多的工作.在http://stackoverflow.com/questions/9676821/how-to-i-regex-match-a-list-reference-in-python上查看一些答案下的讨论. (2认同)