如何用python字符串减少多个条件

2024-04-16 09:50:26 发布

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

我怎样才能减少这种情况?你知道吗

item始终是一个字符串

for item in list_of_items:
    if ('beans' in item or 'apple' in item or 'eggs' in item or 'banana' in item) and ('elephant' not in item) or 'chicken' not in item:
                print(item)

我的意思是,我能不能给你一张单子来检查每一种可能性?你知道吗


Tags: orof字符串inappleforifnot
3条回答

可以将any与生成器或列表一起使用:

if any(word in item for word in ['apple', 'beans', 'eggs', 'banana', 'elephant', 'chicken')):

第一部分可以使用any。你知道吗

然而,第二部分不能减少

if any(w in item for w in ('beans', 'apple', 'eggs', 'banana')) and ('elephant' not in item) or 'chicken' not in item:

对你的情况没有帮助,但你应该知道,所有的都是有用的。你知道吗

您可以将这个if 'a' not in item and 'b' not in item减少到if all(w not in item for w in ('a', 'b')

使用list-comprehension

good_items = ['beans','apple','eggs','banana', 'elephant', 'chicken']
list_of_items = ['apple', 'grapes', 'elephant', 'chicken']

print([x for x in list_of_items if x in good_items and x not in ['elephant', 'chicken']])

输出

['apple']

相关问题 更多 >