簡體   English   中英

如何檢查列表是否僅包含某個項目

[英]How to check if a list ONLY contains a certain item

我有一個名為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'放在那里的代碼中,這是錯誤的。 有沒有簡單的替代品? 我試過幾個相似的詞。

使用builtin 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'

你可以查看清單的長度

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM