 Giperboloid -4 years ago 65
Python Question

# How to apply different operations to different columns of a matrix?

I have a nested list as a matrix. To each column's item of it I need to apply the same operation but one of the operation's argument depends on the column, so it's variable., and is contained in a list. What should I use for that?

Example:

``````arg_list = [1,2,3]

matrix = [[1,2,3],
[1,3,5],
[6,7,2],
[1,4,2]]
``````

Result of subtraction:

``````matrix = [[0,0,0],
[0,1,2],
[5,5,-1],
[0,2,-1]]
`````` Willem Van Onsem

You can use a list of lambda expressions for the operations you want to carry out like:

``````operations = [lambda x:x*2,lambda x:x+1,lambda x:x//3]
``````

so here we multiply the first column by two, we increment the second column and we divide the third column by three.

Now we can use the following list comprehension to generate a new matrix:

``````new_matrix = [[f(x) for f,x in zip(operations,row)] for row in matrix]
``````

``````matrix = [[1,2,3],
[1,3,5],
[6,7,2],
[1,4,2]]
``````

then the `new_matrix` is:

``````>>> [[f(x) for f,x in zip(operations,row)] for row in matrix]
[[2, 3, 1], [2, 4, 1], [12, 8, 0], [2, 5, 0]]
``````

or more syntactically:

``````new_matrix = [[2,  3, 1],
[2,  4, 1],
[12, 8, 0],
[2,  5, 0]]
``````

In case you have however a generic function:

``````def f(column,x):
# ... column is the index (starting by 0)
return column+x # an example
``````

You can use enumerate:

``````new_matrix = [[f(col,x) for col,x in enumerate(row)] for row in matrix]
``````

In your case you can thus write:

``````def f(column,x):
return x-arg_list[column]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download