我有一个名为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'
当然,在那段代码中放置“only”是错误的。有没有一个简单的替代方案?我已经尝试了几个类似的词。
我有一个名为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'
all()
函数。if bag and all(elem == "drink" for elem in bag):
print("Only 'drink' is in the bag")
all()
函数的定义如下:
def all(iterable):
for element in iterable:
if not element:
return False
return True
出于这个原因,空列表将返回True。因为没有元素,它将完全跳过循环并返回True。因为这种情况,您必须添加一个明确的and len(bag)
或and bag
来确保袋子不是空的(()
和[]
是类似false的)。set
。if set(bag) == {['drink']}:
print("Only 'drink' is in the bag")
或者,类似地:
if len(set(bag)) == 1 and 'drink' in bag:
print("Only 'drink' is in the bag")
所有这些都适用于列表中的0个或多个元素。
any
和!=
替换了它,这样在空列表上不会失败 :) - Goodiesand len(bag)
。 - Goodiesif bag == ["drink"]:
print 'There is only a drink in the bag'
else:
print 'There is something else other than a drink in the bag'
如果你想检查列表中是否包含任何一个大于零的相同项"drink"
,你可以计算它们的数量并将其与列表长度进行比较:
if bag.count("drink") == len(bag) > 0:
print 'There are only drinks in the bag'
else:
print 'There is something else other than a drink in the bag'
你可以检查列表的长度
if len(bag) == 1 and "drink" in bag:
#do your operation.