如果L中的'a'或'b',其中L是一个列表(Python)

Bri*_*ach 7 python

我遇到以下逻辑问题:

让我们说我有一个清单 L = ['a', 'b', 'c']


这两个项目都在列表中......

if ('a' or 'b') in L:
    print 'it\'s there!'
else:
    print 'No sorry'
Run Code Online (Sandbox Code Playgroud)

版画 It's there!


只有第一个项目在列表中...

if ('a' or 'd') in L:
    print 'it\'s there!'
else:
    print 'No sorry'
Run Code Online (Sandbox Code Playgroud)

版画 It's there!


列表中没有任何项目......

if ('e' or 'd') in L:
    print 'it\'s there!'
else:
    print 'No sorry'
Run Code Online (Sandbox Code Playgroud)

版画 No sorry


这是令人困惑的一个只有列表中的第二项......

if ('e' or 'a') in L:
    print 'it\'s there!'
else:
    print 'No sorry'
Run Code Online (Sandbox Code Playgroud)

版画 No sorry


我不明白为什么这不是一个真实的陈述.这如何概括为具有n个条件的语句或语句?

前额拍打轻松回答3,2,1 ......

Ste*_*ima 22

让我们分解一下表达式:

('e' or 'a')首先检查是否'e'为True.如果是,表达式将返回'e'.如果没有,它将返回'a'.

由于所有非空字符串都返回True,因此该表达式将始终返回'e'.这意味着if ('e' or 'a') in L:可以翻译成if 'e' in L,在这种情况下是False.

检查列表是否包含一组值的至少一个值的更通用的方法是使用any与生成器表达式耦合的函数.

if any(c in L for c in ('a', 'e')):
Run Code Online (Sandbox Code Playgroud)


aIK*_*Kid 5

使用此代替:

 if 'a' in L or 'b' in L:
Run Code Online (Sandbox Code Playgroud)

如果我们要检查所有这些“项目”是否都在列表中,all并且生成器理解者是您的朋友:

items = 'a', 'b', 'c'
if all(i in L for i in items):
Run Code Online (Sandbox Code Playgroud)

或者,如果这些项目中有任何一项,请使用any:

if any(i in L for i in items)
Run Code Online (Sandbox Code Playgroud)