如何检查列表是否只包含特定项

2024-04-23 22:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个单子叫包。我想知道里面是否只有一个特别的东西。

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”,那就错了。有什么简单的替代品吗?我试过几个类似的词。


Tags: the代码inonlyifiselsesomething
3条回答

您可以检查列表的长度

if len(bag) == 1 and "drink" in bag:
    #do your operation.

使用内置的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,以确保包不是空的(()[]是假的)。

此外,还可以使用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个或多个元素。

您可以直接使用仅包含此项的列表检查相等性:

if 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'

相关问题 更多 >