1

I have an 2D array to do some calculation for each element, which in this format:

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

My expected results is as follow after calculation:

a_new = [[2, 6, 3], [5, 12, 6], [8, 18, 9]]

I wrote the following codes:

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.

However, it has the error message:

SyntaxError: invalid syntax

How to amend the code to get the results I wanted? And also I don't want to import and use NumPy for doing calculation.

4

3 回答 3

1

c +f, (d+f)*g, e定义 atuple并且您在执行以下操作时没有问题:

my_tuple = c +f, (d+f)*g, e

但在列表理解语法中,您需要使用括号保护元组以允许解析,否则 python 不知道参数何时停止:

a_1 = [(c +f, (d+f)*g, e) for (c, d, e) in a]

我得到:

[(2, 6, 3), (5, 12, 6), (8, 18, 9)]

请注意,您的预期输入会显示列表,因此您可能想要的更多:

a_1 = [[c +f, (d+f)*g, e] for (c, d, e) in a]
于 2017-03-02T15:43:51.460 回答
1

方括号可以完成这项工作:

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]]
于 2017-03-02T15:47:32.527 回答
0

如果您希望结果数组与 a_new = [[2, 6, 3], [5, 12, 6], [8, 18, 9]]问题中所述相同,则需要用方括号保护列表推导中的内部操作。

a_new = [[c+f,(d+f)*g,e] for (c,d,e) in a]

您收到了一个无效的语法错误,因为您需要c+f,(d+f)*g,e用方括号括起来以便 Python 识别该操作。

其他一些人指出,您也可以使用括号代替方括号。虽然这不会导致错误,但也不会导致您正在寻找的数组。

如果你使用方括号,你会得到一个列表列表:

[[2, 6, 3], [5, 12, 6], [8, 18, 9]]

如果你使用括号,你会得到一个元组列表:

[(2, 6, 3), (5, 12, 6), (8, 18, 9)]
于 2017-03-02T15:53:37.020 回答