我有一个名为 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”的地方是错误的。有没有简单的替代品?我试过几个类似的词。
最佳答案
使用内置的 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
来保证bag不为空(()
和 []
是假的)。
另外,您可以使用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 个或多个元素。
关于python - 如何检查列表是否只包含某个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36203932/