简体   繁体   中英

Check if item in list

I have a function like this:

def checks(a,b):
    for item in a:
        if b[1] == item[1]:
           return True
        else:
           return False

I want to check if the second value of b is in the second value of item in a such as:

checks(['5v','7y'],'6y')
>>> True

But the code I have right now will return False because I believe it's comparing '6y' with '5v' . How do I solve this?

You're returning True at the right spot, but if the first item doesn't match, the function returns False immediately instead of continuing with the loop. Just move the return False to the end of the function, outside of the loop:

def checks(a,b):
    for item in a:
        if b[1] == item[1]:
           return True

    return False

True will be returned if an item is matched and False will be returned if the loop finishes without a match.

Anyways, that explains why your code wasn't working, but use any as suggested by others to be Pythonic. =)

This can be expressed in a simpler way:

def checks(a, b):
    return any(b[1] == item[1] for item in a)

You could use any() here:

def checks(a,b):
    return any (b[1] == item[1] for item in a)

>>> checks(['5v','7y'],'6y')
True
>>> checks(['5v','7z'],'6y')
False

Help on any :

>>> print any.__doc__
any(iterable) -> bool

Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.

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