Python内置的"all"标记带发电机 [英] Python builtin "all" with generators

查看:71
本文介绍了Python内置的"all"标记带发电机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用python的全部"和生成器时遇到以下问题:

I have the following problem with python's "all" and generators:

G = (a for a in [0,1])
all(list(G))   # returns False - as I expected

但是:

G = (a for a in [0,1])
all(G)         # returns True!

有人可以解释吗?

更新: 我发誓我明白了!检查一下:

UPDATE: I swear I get this! Check this out:

In [1]: G = (a for a in [0,1])

In [2]: all(G)
Out[2]: True

我正在将Python 2.6.6与IPython 0.10.2一起使用,所有这些都安装在Python(x,y)包中.奇怪的是,当我使用Spider IDE时,我得到了"True"(上面),而在纯控制台中得到了"False".

I am using Python 2.6.6 with IPython 0.10.2, all installed within the Python(x,y) package. Strangely enough, I get "True" (above) when I use the Spider IDE, and "False" in pure console...

更新2: 正如DSM指出的那样,这似乎是一个麻木的问题. Python(x,y)加载numpy,而all(G)实际上是在调用numpy.all(G),而不是内置的all().一个快速的解决方法是编写:

UPDATE 2: As DSM pointed out, it seems to be a numpy problem. Python(x,y) loads numpy, and all(G) was actually calling numpy.all(G) rather then the builtin all(). A quick workaround is to write:

__builtins__.all(G)

谢谢大家的帮助!

-maciej

推荐答案

啊哈!

Python(x,y)是否会导入numpy? [看起来像.]

Does Python(x,y) happen to import numpy? [It looks like it.]

Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> 
>>> G = (a for a in [0,1])
>>> all(G)
False
>>> from numpy import all
>>> 
>>> G = (a for a in [0,1])
>>> all(G)
True
>>> 

这是 Robert Kern 的解释:

[all --ed]可以在数组上工作,并且可以将其转换为数组 调用等效于numpy.asarray()的C API.有很多 asarray()中的魔术和特殊情况,以便解释嵌套 Python序列为数组.当我们拥有魔力时,魔力效果很好 具有已知长度的序列;当给定一个 长度未知的任意迭代器.所以我们平底锅.不幸的是 发生然后是asarray()看到一个它无法解释的对象 作为一个序列,变成一个真实的数组,所以它构成了一个秩为0的数组 以iterator对象作为值.计算结果为True.

It [all --ed] works on arrays and things it can turn into arrays by calling the C API equivalent of numpy.asarray(). There's a ton of magic and special cases in asarray() in order to interpret nested Python sequences as arrays. That magic works fairly well when we have sequences with known lengths; it fails utterly when given an arbitrary iterator of unknown length. So we punt. Unfortunately, what happens then is that asarray() sees an object that it can't interpret as a sequence to turn into a real array, so it makes a rank-0 array with the iterator object as the value. This evaluates to True.

这篇关于Python内置的"all"标记带发电机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆