Create list of square powers of numbers in range u

2019-05-01 23:11发布

问题:

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.

回答1:

You'd be better off using list comprehension:

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


回答2:

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:

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:

>>> (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>
>>>