Python: One-Liner to perform operations on elements in a 2d array (list of lists)?

I have a list of lists, each of which contains a different number of lines. I would like to (efficiently) convert all of this into whole ones, but I feel a little tight since I cannot get it to work for life. I tried: newVals = [int (x) for x in [row for rows in values]]

Where 'values' is a list of lists. He constantly says that x is a list and therefore cannot be an argument if int (). Obviously I'm doing something stupid here, what is it? Is there an accepted idiom for this kind of thing?

+11
python arrays matrix 2d
source share
5 answers

This leaves ints nested

[map(int, x) for x in values] 

If you want them flattened, it’s not difficult either

for Python3 map() returns an iterator. you can use

 [list(map(int, x)) for x in values] 

but you may prefer to use a nested LC in this case

 [[int(y) for y in x] for x in values] 
+12
source share

What about:

 >>> a = [['1','2','3'],['4','5','6'],['7','8','9']] >>> [[int(j) for j in i] for i in a] [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 
+9
source share

You just use the wrong order and brackets - should be:

 inputVals = [['1','2','3'], ['3','3','2','2']] [int(x) for row in inputVals for x in row] 

Or if you need a list of output list, then:

 map(lambda row: map(int, row), inputVals) 
+1
source share

An ugly way is to use evalf:

 >>> eval(str(a).replace("'","")) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

If you do not mind all your numbers in one array, you can go:

 >>> a = [['1','2','3'],['4','5','6'],['7','8','9']] >>> map(int,sum(a,[])) [1, 2, 3, 4, 5, 6, 7, 8, 9] 
0
source share

Another workaround

 a = [[1, 2, 3], [7, 8, 6]] list(map(lambda i: list(map(lambda j: j - 1, i)), a)) [[0, 1, 2], [6, 7, 5]] #output 
0
source share

All Articles