Jasper
Jasper

Reputation: 628

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...

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.

Upvotes: 0

Views: 107

Answers (3)

Patrick
Patrick

Reputation: 1148

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.

Upvotes: 1

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

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

Upvotes: 1

Brent Newey
Brent Newey

Reputation: 4509

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

Upvotes: 1

Related Questions