简体   繁体   English

我想不通这个 function 有什么问题?

[英]I can't figure out what is wrong with this function?

This is what it should return这是它应该返回的

Returns True if all items are truthy.如果所有项目都是真实的,则返回 True。

Examples:
>>> all_true([1, True, 'oregonstate'])
True
>>> all_true([0, 1, 2])
False
"""

This is what I have written这是我写的

def all_true(items):
    for i in items:
        if i == True:
            return True
        else:
          return False
    pass

Not sure why it is not working, can someone help?不知道为什么它不起作用,有人可以帮忙吗?

Your function just returns the truthiness of the first item in the list, since it always returns on the first iteration.您的 function 只返回列表中第一项的真实性,因为它总是在第一次迭代时返回。

You want to do something like this:你想做这样的事情:

def all_true(items):
    for i in items:
        if not i:
            return False
    return True

Note that this all_true function already exists in Python. It is the the built-in all function.注意这个all_true function已经存在于Python中,是内置的all function。

Two problems.两个问题。 First, you are returning on the first True thing.首先,您返回的是第一个True事物。 In fact, you are returning either True or False on the first thing, regardless.事实上,不管怎样,您首先返回的不是True就是False Since you return on both the if and its else clauses, the loop will always return on the first iteration.由于您同时返回了if和它的else子句,因此循环将始终在第一次迭代时返回。 A bit more subtle, but if there aren't any values in the list, it will return None .更微妙一点,但如果列表中没有任何值,它将返回None

Second, if you want "truthy", don't compare specifically to True .其次,如果您想要“真实”,请不要专门与True进行比较。 foo == True is False . foo == TrueFalse Instead, just let the if do the boolean test相反,让if做 boolean 测试

def all_true(items):
    for i in items:
        if not i:
            return False
    return True

all and any are builtin functions that do the same thing. allany是做同样事情的内置函数。 It would generally be preferable to use them.通常最好使用它们。

"All items are truthy" is logically equivalent to "no items are falsy." “所有项目都是真实的”在逻辑上等同于“没有项目是虚假的”。

def all_true(items):
    for i in items:
        if not i:
            return False
    return True

Because 0 is falsy.因为 0 是假的。 Also there's no need to implement your own function for that, use Python's built–in all() function instead!此外,无需为此实现您自己的 function,而是使用 Python 的内置all() function!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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