简体   繁体   English

Python生成器中的意外输出

[英]Unexpected output in Python Generators

I am trying to figure out generators in Python and i am trying to filter the list and square them and return the output. 我试图找出Python中的生成器,我试图过滤列表并对它们进行平方并返回输出。

list = [1, 4, -5, 10, -7, 2, 3, -1]

def square_generator(optional_parameter):
    return (x ** 2 for x in list if x > optional_parameter)
g = (square_generator(i) for i in list)

h = square_generator(0)
print h

What i am doing wrong ? 我做错了什么?

When you define a generator you must iterate over it like so: 定义生成器时,必须迭代它,如下所示:

for x in h:
    print x

If you just try to print the generator then you'll get the object: 如果您只是尝试打印生成器,那么您将获得该对象:

<generator object <genexpr> at 0x02A4FB48>

If you wanted to produce a list, just use a list comprehension: 如果要生成列表,只需使用列表推导:

def square_generator(optional_parameter):
    return [x ** 2 for x in somelist if x > optional_parameter]

or turn call list() on the generator (provided you didn't use list as a local name): 或者在生成器上转动调用list() (前提是您没有使用list作为本地名称):

list(h)

Your generator is working just fine otherwise: 你的发电机工作正常,否则:

>>> somelist = [1, 4, -5, 10, -7, 2, 3, -1]
>>> def square_generator(optional_parameter):
...     return (x ** 2 for x in somelist if x > optional_parameter)
... 
>>> list(square_generator(0))
[1, 16, 100, 4, 9]

your square_generator function returns a generator object. square_generator函数返回一个生成器对象。 Generators are iterators, and they are as such not lists but objects containing rules for generating the next element of a sequence. 生成器是迭代器,它们不是列表,而是包含用于生成序列的下一个元素的规则的对象。

So, when your function returns, it does not calculate the squares. 因此,当您的函数返回时,它不会计算平方。 They are calculated only when needed. 它们仅在需要时计算。 Therefore you need to iterate over the sequence to get the elements. 因此,您需要遍历序列以获取元素。 They simply does not exist before you request to see them. 在您要求查看它们之前,它们根本不存在。

This also means that when you have iterated over the list it disappears. 这也意味着当你遍历列表时它会消失。 If you want it to be persistent you have to look at Martin Pieters' answer ie use a list instead of a generator/iterator. 如果你想要它是持久的,你必须看看Martin Pieters的答案,即使用列表而不是生成器/迭代器。

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

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