使用列表中的任何值进行逻辑检查?

2024-05-19 07:22:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我怎样才能有一个逻辑检查,它检查的是动作中的“咀嚼”以及列表中的任何值?例如,我想打印“Yum!”动作是“嚼橘子”还是“嚼干”。在


Tags: andinifactionelselistprint动作
3条回答

为什么不使用内置的^{}函数?在我看来,以下几点很像Python:

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

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

当然,仅仅搜索简单的子串可能会得到一些奇怪的结果。例如,"jerkeyblahchew"仍然与"Yum!"类别匹配。您可能需要将action拆分成单词,并查找紧跟在"chew"后面的食物名称(正如@Peter Lyons在他对简单情况的回答中所建议的,其中前两个单词应该是"chew X")。在

忽略顺序,您可以使用以下类似的方法,只关注空格分隔的单词(并进一步忽略大写/小写):

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

首先,请不要使用list作为变量名。这是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!"

相关问题 更多 >

    热门问题