检查python列表的内容

Roc*_*e28 1 python collections list conditional-statements

使用python 2.7.4

让我们说我有一个清单

list = ['abc', 'def']
Run Code Online (Sandbox Code Playgroud)

我想找到它是否包含某些东西.所以我尝试:

 [IN:] 'abc' in list
[OUT:] True
 [IN:] 'def' in list
[OUT:] True
 [IN:] 'abc' and 'def' in list
[OUT:] True
Run Code Online (Sandbox Code Playgroud)

但是当我list.pop(0)并重复上一次测试:

 [IN:] 'abc' and 'def in list
[OUT:] True
Run Code Online (Sandbox Code Playgroud)

即使:

list = ['def']
Run Code Online (Sandbox Code Playgroud)

谁知道为什么?

Ash*_*ary 5

那是因为:

abc' and 'def' in list
Run Code Online (Sandbox Code Playgroud)

相当于:

('abc') and ('def' in list) #Non-empty string is always True
Run Code Online (Sandbox Code Playgroud)

使用'abc' in list and 'def' in list或用于您也可以使用的多个项目all()

all(x in list for x in ('abc','def'))
Run Code Online (Sandbox Code Playgroud)

不要list用作变量名,它是内置类型.