使用生成器创建范围内数字的平方幂列表

时间:2011-01-08 23:00:53

标签: python range generator

我想使用generator重写这部分代码:

basic = []
for x in range(0,11):
    basic.append(x**2)

我该怎么做?试过:

basic.append(x**2 for x in range(0,11))

但它会在x**2部分引发语法错误。

4 个答案:

答案 0 :(得分:16)

你最好使用列表理解:

basic = [x*x for x in range(11)]

答案 1 :(得分:8)

你错了;你的代码不会产生语法错误,它只是做错了:

>>> basic = []
>>> basic.append(x**2 for x in range(0,11))
>>> basic
[<generator object <genexpr> at 0x01E9AD78>]
>>>

如果必须使用发电机:

>>> basic = list(x**2 for x in range(0,11))
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>

使用列表理解更简单:

>>> basic = [x**2 for x in range(0,11)]
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>

答案 2 :(得分:1)

使用extend而非append

>>> basic=[]
>>> basic.extend(x**2 for x in range(11))
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

更好的是:

>>> basic = [x**2 for x in range(11)]
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

答案 3 :(得分:0)

>>> (x**2 for x in xrange(0,11))
<generator object <genexpr> at 0xb7387734>

>>> def gen():
...     for x in xrange(0,11):
...             yield x**2
... 
>>> gen
<function gen at 0xb738a0d4>
>>> gen()
<generator object gen at 0xb7387734>
>>>