python - 使用 Python 且不使用 NumPy 的 2D 数组元素计算

标签 python arrays calculation

我有一个二维数组来对每个元素进行一些计算,其格式如下:

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/

相关文章:

python - 在django中查询数组

python - 如何从文本文件导入(整数)列表的列表并以数学方式处理它们?

python - 找不到域 'django' 的翻译文件

php - 使用PHP的“Notice: Undefined variable”,“Notice: Undefined index”和“Notice: Undefined offset”

linux - Bash - 用给定的日期计算

python - 如何将模块导入到 Python 上导入的其他脚本中?

arrays - 将值附加到 struct coldfusion 中的现有键

javascript - 多个数组到多维数组

javascript - 找时间在一张图中写一个数字

python - 为什么以下代码给出不同的输出? (大数的平方根)