简体   繁体   English

清单python中的字符串内容

[英]Something from string in list python

I have a list with keywords id = ['pop','ppp','cre'] and now I am going through a bunch of files/large strings and if any of these keywords are in these files than I have to be able to do something... 我有一个包含关键字id = ['pop','ppp','cre']的列表,现在我要遍历一堆文件/大字符串,如果这些关键字中有任何一个比我必须的做某事...

like: 喜欢:

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

But i think now all of these 3 or later maybe more have to be in the dataset and not just only one. 但是我认为现在所有这3个或更高版本可能都必须包含在数据集中,而不仅仅是一个。

You can use all to make sure all the values in your id list are in the dataset: 您可以使用all来确保id列表中的所有值都在数据集中:

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

Your code as it stands will actually look through dataset for the entire list " ['pop', 'ppp', 'cre'] ". 您的代码实际上将通过dataset查找整个列表“ ['pop', 'ppp', 'cre'] ”。 Why don't you try something like this: 你为什么不尝试这样的事情:

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

Edit: 编辑:

This will probably be more efficient: 这可能会更有效:

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

Assuming |dataset| 假设|数据集| > |id| > | id | and you break out of the loop when you find a match. 当您找到匹配项时,您就会跳出循环。

Since you mentioned that you need to check any word within dataset then I think any() built-in method will help : 既然您提到需要检查数据集中的任何单词,那么我认为any()内置方法会有所帮助

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

Or: 要么:

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

And: 和:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM