开发者

Using python to return a list of squared integers

I'm looking to write a function that takes the integers within a list, such as [1, 2, 3], and returns a new list with the squared integers; [1, 4, 9]

How would I go about this?

PS - just before I wa开发者_高级运维s about to hit submit I noticed Chapter 14 of O'Reilly's 'Learning Python' seems to provide the explanation I'm looking for (Pg. 358, 4th Edition)

But I'm still curious to see what other solutions are possible


You can (and should) use list comprehension:

squared = [x**2 for x in lst]

map makes one function call per element and while lambda expressions are quite handy, using map + lambda is mostly slower than list comprehension.

Python Patterns - An Optimization Anecdote is worth a read.


Besides lambda and list comprehensions, you can also use generators. List comprehension calculates all the squares when it's called, generators calculate each square as you iterate through the list. Generators are better when input size is large or when you're only using some initial part of the results.

def generate_squares(a):
    for x in a:
        yield x**2 

# this is equivalent to above
b = (x**2 for x in a)


squared = lambda li: map(lambda x: x*x, li)


You should know about map built-in which takes a function as the first argument and an iterable as the second and returns a list consisting of items acted upon by the function. For e.g.

>>> def sqr(x):
...     return x*x
... 
>>> map(sqr,range(1,10))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> 

There is a better way of writing the sqr function above, namely using the nameless lambda having quirky syntax. (Beginners get confused looking for return stmt)

>>> map(lambda x: x*x,range(1,10))
[1, 4, 9, 16, 25, 36, 49, 64, 81]

Apart from that you can use list comprehension too.

result = [x*x for x in range(1,10)]


a = [1, 2, 3]
b = [x ** 2 for x in a]


good remark of kefeizhou, but then there is no need of a generator function, a generator expression is right:

for sq in (x*x for x in li):
   # do


You can use lambda with map to get this.

lst=(3,8,6)
sqrs=map(lambda x:x**2,lst)
print sqrs
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜