简体   繁体   中英

Check if a string contains one or more of list values in python

I have a list and a string as follows.

mylist = ["tim tam", "yogurt", "strawberry"]
mystring = "I love to eat tim tam"

Now I want to check if mystring contains one or more words in mylist . If it contains the flag variable should be true, if not false.

My current code is as follows.

if mylist in mystring:
    flag = 1
else:
    flag = 0

However, I get the error TypeError: argument of type 'method' is not iterable . Not sure why it happens. Please help me.

You can use a generator expression in any to check each substring against your original string

>>> flag = any(i in mystring for i in mylist)
>>> flag
True

If you want an int instead of a bool you can modify the above to

>>> flag = int(any(i in mystring for i in mylist))
>>> flag
1

You can use str.contains- or lambda-function for filtering (I use it for DataFrame).

df=df.str.contains("keyword1|keyword2|keyword3", na=False)]

or

ddf[df.apply(lambda r: r.str.contains('keyword1|keyword2|keyword3', case=False).any(), axis=1)] 

Example:

mylist = 'tim tam|yogurt|strawberry'   
df = pd.DataFrame(df[df[[0,1,2,3...]].apply(lambda r: r.str.contains(mylist, case=False).any(), axis=1)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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