Create list of square powers of numbers in range u

2019-05-01 22:52发布

I'd like to rewrite this part of code using generator :

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

How can I do this ? Tried :

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

but it raises syntax error in x**2 part.

4条回答
ら.Afraid
2楼-- · 2019-05-01 23:26

You are mistaken; your code doesn't produce a syntax error, it just does the wrong thing:

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

If you must use a generator:

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

It's simpler to use a list comprehension:

>>> basic = [x**2 for x in range(0,11)]
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
查看更多
时光不老,我们不散
3楼-- · 2019-05-01 23:27

Use extend not append.

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

Better yet:

>>> basic = [x**2 for x in range(11)]
>>> basic
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
查看更多
唯我独甜
4楼-- · 2019-05-01 23:31
>>> (x**2 for x in xrange(0,11))
<generator object <genexpr> at 0xb7387734>

or

>>> def gen():
...     for x in xrange(0,11):
...             yield x**2
... 
>>> gen
<function gen at 0xb738a0d4>
>>> gen()
<generator object gen at 0xb7387734>
>>> 
查看更多
贼婆χ
5楼-- · 2019-05-01 23:33

You'd be better off using list comprehension:

basic = [x*x for x in range(11)]
查看更多
登录 后发表回答