1

我有这样的功能:

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

我想检查 b 的第二个值是否在 a 的 item 的第二个值中,例如:

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

但是我现在拥有的代码会返回False,因为我相信它'6y''5v'. 我该如何解决这个问题?

4

3 回答 3

3

True在正确的位置返回,但如果第一项不匹配,该函数将False立即返回,而不是继续循环。只需将 移动return False到函数的末尾,在循环之外:

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

    return False

True如果匹配项False将返回,如果循环结束但没有匹配项将返回。

无论如何,这解释了为什么您的代码不起作用,而是any按照其他人的建议使用 Pythonic。=)

于 2013-05-25T04:05:18.657 回答
2

这可以用更简单的方式表达:

def checks(a, b):
    return any(b[1] == item[1] for item in a)
于 2013-05-25T04:05:30.910 回答
2

你可以any()在这里使用:

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

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

帮助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.
于 2013-05-25T04:09:08.710 回答