我有一个二维数组来对每个元素进行一些计算,其格式如下:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
计算后我的预期结果如下:
a_new = [[2, 6, 3], [5, 12, 6], [8, 18, 9]]
我编写了以下代码:
f = 1
g = 2
a_1 = [c +f, (d+f)*g, e for (c, d, e) in array] #I expect this can bring the results to form the format I want.
但是,它有错误消息:
SyntaxError: invalid syntax
如何修改代码才能得到我想要的结果?而且我不想导入和使用 NumPy 进行计算。
最佳答案
方括号就可以完成这项工作:
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
f = 1
g = 2
a_1 = [[c +f, (d+f)*g, e] for (c, d, e) in array]
结果:
a_1
[[2, 6, 3], [5, 12, 6], [8, 18, 9]]
关于python - 使用 Python 且不使用 NumPy 的 2D 数组元素计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42559748/