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

Viewed 23541

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?

6 Answers

In order to map list with any number of dimensions you could use numpy.apply_over_axes

import numpy as np
np.apply_over_axes(lambda x,_:x*2, np.array([[1,2,3],[5,2,1]]),[0])
--------------------
array([[ 2,  4,  6],
       [10,  4,  2]])

Unfortunately that doesn't work if you also need to change variable type. Didn't find any library solution for this, so here is the code to do that:

def map_multi_dimensional_list(l, transform):
    if type(l) == list and len(l) > 0:
        if type(l[0]) != list:
            return [transform(v) for v in l]
        else:
            return [map_multi_dimensional_list(v, transform) for v in l]
    else:
        return []
            
map_multi_dimensional_list([[[1,2,3],[5,2,1]],[[10,20,30],[50,20,10]]], lambda x:x*2)
------------------
[[[2, 4, 6], [10, 4, 2]], [[20, 40, 60], [100, 40, 20]]]
Related