问题描述
我正在寻找一个函数,该函数接受列表中的整数,例如[1、2、3],并返回带有平方整数的新列表; [1,4,9]
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]
我将如何处理?
PS-在我即将提交之前,我注意到O'Reilly的"Learning Python"的第14章似乎提供了我想要的解释(第358页,第4版)
PS - just before I was 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
每个元素调用一个函数,虽然lambda
表达式非常方便,但是使用map
+ lambda
的速度通常比列表理解要慢.
map
makes one function call per element and while lambda
expressions are quite handy, using map
+ lambda
is mostly slower than list comprehension.
Python模式-优化轶事 是值得一读.
Python Patterns - An Optimization Anecdote is worth a read.
这篇关于使用python返回平方整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!