基本上我希望它是这样的:
- 检查字符串是否包含列表中的字符串/项目之一的循环。基本上,“当列表的当前索引在找到时返回 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?
好吧,问题基本上是,我该怎么做。抱歉我的格式和英语不好等等。
例子:
我有一个字符串“La die la Blablabla and flowers are red”
我有一个数组 TheArray,['Blablabla', 'thisonewillnotbefound', 'flowers', 'thisonenoteither', 'red']
我需要一个遍历数组中每一项的循环,每当它找到其中存在的一项时,它就会被附加到一个全新的列表中。
请您参考如下方法:
这将为您提供在文本中找到该词的列表的索引列表
>>> 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]
enumerate将采用一个迭代器并给出另一个带有元组的迭代器,其中第一个元素是从 0 开始的索引,第二个是您传递给它的迭代器中的一个元素。
[i for i, x in ...] 是一个 list comprehension只是编写 for 循环的一种简短形式
