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 i开发者_如何学JAVAn these files than I have to be able to do something...
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.
You can use all
to make sure all the values in your id
list are in the dataset:
id = ['pop', 'ppp', 'cre']
if all(i in dataset for i in id):
print id
Since you mentioned that you need to check any word within dataset then I think any() built-in method will help:
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
Your code as it stands will actually look through dataset
for the entire list "['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| and you break out of the loop when you find a match.
精彩评论