开发者

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

开发者 https://www.devze.com 2023-03-13 09:58 出处:网络
I have a list of lists, each containing a different number of strings. I\'d like to (efficientl开发者_开发知识库y) convert these all to ints, but am feeling kind of dense, since I can\'t get it to wor

I have a list of lists, each containing a different number of strings. I'd like to (efficientl开发者_开发知识库y) 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?


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]


How 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]]


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


You simply use incorrect order and parenthesis - should be:

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

Or if you need list of list at the output then:

map(lambda row: map(int, row), inputVals)


an ugly way is to use evalf:

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

if you don't mind all your numbers in one array you could go:

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


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]]]
0

精彩评论

暂无评论...
验证码 换一张
取 消