C. Pun
C. Pun

Reputation: 23

2D array element calculation using Python and without NumPy

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.

Upvotes: 1

Views: 1027

Answers (3)

Louis P. Dartez
Louis P. Dartez

Reputation: 101

if you want your resulting array to be a_new = [[2, 6, 3], [5, 12, 6], [8, 18, 9]] as stated in your question then you need to protect the inner operation in the list comprehension with square brackets.

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

You were getting an invalid syntax error because you needed to wrap c+f,(d+f)*g,e in square brackets for Python recognize the operation.

Some others have pointed out that you could also use parentheses instead of square brackets. While this won't result in an error, it will also not result in the array that you're looking for.

If you use square brackets you will get a list of lists:

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

If you use parentheses you will get a list of tuples:

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

Upvotes: 0

Stefan T. Huber
Stefan T. Huber

Reputation: 51

Square brackets will do the job:

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]

Results in:

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

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140188

c +f, (d+f)*g, e define a tuple and you have no problem when doing:

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

but in the list comprehension syntax, you need to protect the tuple using parentheses to allow parsing, else python doesn't know when the argument stops:

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

I get:

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

Note that your expected input shows lists, so maybe that is more that you want:

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

Upvotes: 1

Related Questions