简体   繁体   中英

How to check if a list ONLY contains a certain item

I have a list called bag. I want to be able to check if only a particular item is in it.

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'

Of course, where I put 'only' in the code there, it is wrong. Is there any simple replacement of that? I have tried a few similar words.

Use the builtin all() function.

if bag and all(elem == "drink" for elem in bag):
    print("Only 'drink' is in the bag")

The all() function is as follows:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

For this reason, an empty list will return True. Since there are no elements, it will skip the loop entirely and return True. Because this is the case, you must add an explicit and len(bag) or and bag to ensure that the bag is not empty ( () and [] are false-like).

Also, you could use a set .

if set(bag) == {['drink']}:
    print("Only 'drink' is in the bag")

Or, similarly:

if len(set(bag)) == 1 and 'drink' in bag:
    print("Only 'drink' is in the bag")

All of these will work with 0 or more elements in the list.

You could directly check for equality with a list that only contains this item:

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'

Alternatively if you want to check whether the lists contains any number greater than zero of the same item "drink" , you can count them and compare with the list length:

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'

You can check length of list

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM