Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic check using any value from a list?

list = ["apples", "oranges", "jerky", "tofu"]

if "chew" in action and list[:] in action:
    print "Yum!"
else:
    print "Ew!"

How do I have a logic check where it checks for "chew" in action as well as ANY value in list? For example, I want to print "Yum!" whether action is "chew oranges" or "chew jerky".

like image 940
TomKo Avatar asked Mar 18 '26 21:03

TomKo


2 Answers

Why not use the builtin any() function? The following seems quite Pythonic to me:

foods = ["apples", "oranges", "jerky", "tofu"]

if "chew" in action and any(f in action for f in foods):
    print "Yum!"
else:
    print "Ew!"

Of course, just searching for simple substrings may give some weird results. For instance "jerkeyblahchew" would still match the "Yum!" category. You'd probably want to split action into words, and look for food names that immediately follow "chew" (as @Peter Lyons suggests in his answer for the simple case where the first two words would be "chew X").

Ignoring order, you could focus just on space-separated words (and further ignore capital/lowercase) by using something like the following:

foods = ["apples", "oranges", "jerky", "tofu"]
action_words = set(word.lower() for word in action.split())

if "chew" in action_words and any(f in action_words for f in foods):
    print "Yum!"
else:
    print "Ew!"
like image 111
Greg Haskins Avatar answered Mar 20 '26 10:03

Greg Haskins


if "chew" in action and action.split()[1] in list:
    print "Yum!"
else:
    print "Ew!"
like image 34
Peter Lyons Avatar answered Mar 20 '26 10:03

Peter Lyons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!