我有一个名为bag的列表.我希望能够检查是否只有特定的项目.
bag = ["drink"]
if only "drink" in bag:
print 'There is only a drink in the bag'
else:
print 'There is something else other than a drink in the bag'
Run Code Online (Sandbox Code Playgroud)
当然,在那里我把'only'放在那里的代码中,这是错误的.有没有简单的替代品?我试过几个相似的词.
使用内置all()功能.
if bag and all(elem == "drink" for elem in bag):
print("Only 'drink' is in the bag")
Run Code Online (Sandbox Code Playgroud)
该all()功能如下:
def all(iterable):
for element in iterable:
if not element:
return False
return True
Run Code Online (Sandbox Code Playgroud)
因此,空列表将返回True.由于没有元素,它将完全跳过循环并返回True.因为是这种情况,您必须添加一个显式and len(bag)或and bag确保包不是空的(()并且[]是假的).
此外,你可以使用set.
if set(bag) == {['drink']}:
print("Only 'drink' is in the bag")
Run Code Online (Sandbox Code Playgroud)
或者,类似地:
if len(set(bag)) == 1 and 'drink' in bag:
print("Only 'drink' is in the bag")
Run Code Online (Sandbox Code Playgroud)
所有这些都适用于列表中的0个或更多元素.
| 归档时间: |
|
| 查看次数: |
6868 次 |
| 最近记录: |