Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?

I have a list of lists, each containing a different number of strings. I'd like to (efficiently) convert these all to ints, but am feeling kind of dense, since I can't get it to work out for the life of me. I've been trying: newVals = [int(x) for x in [row for rows in values]]

Where 'values' is the list of lists. It keeps saying that x is a list and can therefore not be the argument if int(). Obviously I'm doing something stupid here, what is it? Is there an accepted idiom for this sort of thing?

like image 638
aped Avatar asked Jun 17 '11 05:06

aped


2 Answers

This leaves the ints nested

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

If you want them flattened, that's not hard either

for Python3 map() returns an iterator. You could use

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

but you may prefer to use the nested LC's in that case

[[int(y) for y in x] for x in values]
like image 128
John La Rooy Avatar answered Oct 21 '22 20:10

John La Rooy


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
like image 44
Muhammad Younus Avatar answered Oct 21 '22 21:10

Muhammad Younus