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

aped picture aped · Jun 17, 2011 · Viewed 16.9k times · Source

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?

Answer

John La Rooy picture John La Rooy · Jun 17, 2011

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]