来自python列表中字符串的内容

2024-03-29 09:35:20 发布

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

我有一个关键字id=['pop','ppp','cre']的列表,现在我正在浏览一堆文件/大字符串,如果这些关键字中有任何一个在这些文件中,我就必须能够做些什么。。。你知道吗

比如:

id = ['pop','ppp','cre']
if id in dataset:
         print id

但我认为现在所有这3个或更多的数据都必须在数据集中,而不仅仅是一个。你知道吗


Tags: 文件数据字符串inid列表if关键字
3条回答

既然您提到需要检查数据集中的任何单词,那么我认为any() built-in method will help

if any(word in dataset for word in id):
    # do something

或:

if [word for word in id if word in dataset]:
    # do something

以及:

if filter(lambda word: word in dataset, id):
    # do something

可以使用all确保id列表中的所有值都在数据集中:

id = ['pop', 'ppp', 'cre']
if all(i in dataset for i in id):
    print id

您的代码实际上将通过dataset查找整个列表“['pop', 'ppp', 'cre']”。你为什么不试试这样的方法:

for item in id:
    if item in dataset:
        print id

编辑:

这可能会更有效率:

for item in dataset:
    if item in id:
        print id

假设| dataset |>;| id |,当您找到匹配项时,就会跳出循环。你知道吗

相关问题 更多 >