问题:python any()函数如何工作?

在的python文档页面中,该any()函数的等效代码为:

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

如果以这种形式调用此函数,该函数如何知道我要测试的元素?

any(x > 0 for x in list)

从函数定义中,我只能看到我正在传递一个可迭代的对象。for循环如何知道我在寻找什么> 0

In the python docs page for , the equivalent code for the any() function is given as:

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

How does this function know what element I wanna test if call it in this form?

any(x > 0 for x in list)

From the function definition, all I can see is that I’m passing an iterable object. How does the for loop know I am looking for something > 0?


回答 0

如果您使用any(lst)它,那将lst是可迭代的,这是一些项的列表。如果包含[0, False, '', 0.0, [], {}, None](均具有布尔值False),any(lst)则将为False。如果lst还包含以下任何[-1, True, "X", 0.00001](所有这些评估为True),那么any(lst)True

在您发布的代码中x > 0 for x in lst,这是另一种可迭代的类型,称为生成器表达式。在将生成器表达式添加到Python之前,您已经创建了一个列表理解,它看起来非常相似,但带有[][x > 0 for x in lst]。从lst包含的清单[-1, -2, 10, -4, 20],您可以得到:。由于存在至少一个值,因此此内部值将传递给该函数,该函数将返回。[False, False, True, False, True]anyTrueTrue

但是使用生成器表达式时,Python不再需要创建True(s)and的内部列表,False(s)因为any函数迭代生成器表达式一次生成的值时会生成值。并且,由于any短路,一旦看到第一个True值,它将立即停止迭代。如果lst使用类似方法创建lst = range(-1,int(1e9))(或xrange使用Python2.x),则将特别方便。即使此表达式将生成超过十亿个条目,any但到达时只需要到达第三个条目1,它的值就Truex>0,因此any可以返回True

如果您创建了列表推导,Python首先必须在内存中创建十亿个元素的列表,然后将其传递给any。但是,通过使用生成器表达式,您可以在看到a 或value时就拥有Python的内置函数,例如,anyall尽早推出。TrueFalse

If you use any(lst) you see that lst is the iterable, which is a list of some items. If it contained [0, False, '', 0.0, [], {}, None] (which all have boolean values of False) then any(lst) would be False. If lst also contained any of the following [-1, True, "X", 0.00001] (all of which evaluate to True) then any(lst) would be True.

In the code you posted, x > 0 for x in lst, this is a different kind of iterable, called a generator expression. Before generator expressions were added to Python, you would have created a list comprehension, which looks very similar, but with surrounding []‘s: [x > 0 for x in lst]. From the lst containing [-1, -2, 10, -4, 20], you would get this comprehended list: [False, False, True, False, True]. This internal value would then get passed to the any function, which would return True, since there is at least one True value.

But with generator expressions, Python no longer has to create that internal list of True(s) and False(s), the values will be generated as the any function iterates through the values generated one at a time by the generator expression. And, since any short-circuits, it will stop iterating as soon as it sees the first True value. This would be especially handy if you created lst using something like lst = range(-1,int(1e9)) (or xrange if you are using Python2.x). Even though this expression will generate over a billion entries, any only has to go as far as the third entry when it gets to 1, which evaluates True for x>0, and so any can return True.

If you had created a list comprehension, Python would first have had to create the billion-element list in memory, and then pass that to any. But by using a generator expression, you can have Python’s builtin functions like any and all break out early, as soon as a True or False value is seen.


回答 1

>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True

>>> all(n in 'King and Queen' for n in names)
False

它只是将几行代码简化为一个。您不必编写冗长的代码,例如:

for n in names:
    if n in 'King and john':
       print True
    else:
       print False
>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True

>>> all(n in 'King and Queen' for n in names)
False

It just reduce several line of code into one. You don’t have to write lengthy code like:

for n in names:
    if n in 'King and john':
       print True
    else:
       print False

回答 2

(x > 0 for x in list) 在该函数调用中创建一个生成器表达式,例如。

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

any用途,并在遇到的第一个对象,评估地短路True

(x > 0 for x in list) in that function call creates a generator expression eg.

>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
        print x


True
True
False
True
False

Which any uses, and shortcircuits on encountering the first object that evaluates True


回答 3

这是因为迭代是

(x > 0 for x in list)

请注意,x > 0返回TrueFalse,因此您具有一个可迭代的布尔值。

It’s because the iterable is

(x > 0 for x in list)

Note that x > 0 returns either True or False and thus you have an iterable of booleans.


回答 4

简而言之,any()会完成这项工作:即使遇到列表中一个满足的值,它也会根据条件根据条件返回true,否则返回false。

list = [2,-3,-4,5,6]

a = any(x>0 for x in lst)

print a:
True


list = [2,3,4,5,6,7]

a = any(x<0 for x in lst)

print a:
False

Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.

list = [2,-3,-4,5,6]

a = any(x>0 for x in lst)

print a:
True


list = [2,3,4,5,6,7]

a = any(x<0 for x in lst)

print a:
False

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。