TomKo
TomKo

Reputation: 129

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

Upvotes: 2

Views: 237

Answers (5)

Greg Haskins
Greg Haskins

Reputation: 6794

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!"

Upvotes: 6

Jeannot
Jeannot

Reputation: 1175

Its seems like you want to do some set operation here (intersection).

Assuming action is a basestring containing words:

foods = set(["apples", "oranges", "jerky", "tofu"])
actionWords = set(action.split())

if "chew" in action and foods & actionWords:
    print "Yum!"
else:
    print "Ew!"

the & operator on a set stands for intersection, see python doc.

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61643

x in y means "look at each of the elements of y in turn; is any of them equal to x?" So the logic is obviously not right: list (a bad idea for a variable name, BTW, since that's the name of the type) is a list of strings, and action is a string - the elements of a string are letters, and no letter can be equal to a list of strings.

Upvotes: 0

Bryce Siedschlaw
Bryce Siedschlaw

Reputation: 4226

First off, please don't use list as a variable name. It's a keyword in python


_list = ["apples", "oranges", "jerky", "tofu"]
bools = [True for a in action.split() if a in (_list + ["chew"])]
if True in bools:
    print "Yum!"
else:
    print "Ew!"

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 146154

if "chew" in action and action.split()[1] in list:
    print "Yum!"
else:
    print "Ew!"

Upvotes: 4

Related Questions