Python - 如何检查字符串是否包含列表中的项目,并且当返回true时,将列表中的项目作为索引在循环中可用

Maa*_*ard 1 python

基本上我是多么喜欢它,是:

  • 循环,检查字符串是否包含列表中的一个字符串/项.基本上,"当列表的当前索引在找到时返回true时,将该项作为字符串附加到新列表"

另一篇文章的例子:

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for any("abc" in s for s in some_list):
    #s isn't the index, right?
Run Code Online (Sandbox Code Playgroud)

那么,问题基本上是,我该怎么做才能做到.对不起,我的格式和英语很差,等等.

例:

我有一个字符串 "La die la Blablabla and flowers are red"

我有一个阵列TheArray,['Blablabla', 'thisonewillnotbefound', 'flowers', 'thisonenoteither', 'red']

我需要一个遍历数组中每个项目的循环,每当它找到一个存在于其中的项目时,它将被附加到一个全新的列表中.

Fac*_*sco 10

这将为您提供列表中的索引列表,其中包含在文本中找到的单词

>>> text = 'Some text where the words should be'
>>> words = ['text', 'string', 'letter', 'words']
>>> [i for i, x in enumerate(words) if x in text]
[0, 3]
Run Code Online (Sandbox Code Playgroud)

enumerate 将获取一个迭代器并给另一个带元组,其中第一个元素是从0开始的索引,第二个元素是传递给它的迭代器中的元素.

[i for i, x in ...]是一个list comprehension只是写一个for循环的简短形式