Squaring all elements in a list(对列表中的所有元素进行平方)
问题描述
我被告知
编写一个函数 square(a),它接受一个数字数组 a 并返回一个包含平方的每个值的数组.
Write a function, square(a), that takes an array, a, of numbers and returns an array containing each of the values of a squared.
一开始我有
def square(a):
for i in a: print i**2
但这不起作用,因为我正在打印,并且没有像我被问到的那样返回.所以我尝试了
But this does not work since I'm printing, and not returning like I was asked. So I tried
def square(a):
for i in a: return i**2
但这只是我数组的最后一个数字的平方.我怎样才能让它对整个列表进行平方?
But this only squares the last number of my array. How can I get it to square the whole list?
推荐答案
你可以使用列表推导:
def square(list):
return [i ** 2 for i in list]
或者你可以map
它:
def square(list):
return map(lambda x: x ** 2, list)
或者您可以使用生成器.它不会返回列表,但您仍然可以遍历它,并且由于您不必分配整个新列表,因此它可能比其他选项更节省空间:
Or you could use a generator. It won't return a list, but you can still iterate through it, and since you don't have to allocate an entire new list, it is possibly more space-efficient than the other options:
def square(list):
for i in list:
yield i ** 2
或者您可以执行无聊的旧 for
-循环,尽管这不像某些 Python 程序员所希望的那样惯用:
Or you can do the boring old for
-loop, though this is not as idiomatic as some Python programmers would prefer:
def square(list):
ret = []
for i in list:
ret.append(i ** 2)
return ret
这篇关于对列表中的所有元素进行平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对列表中的所有元素进行平方


基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01