15

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?

user213544
  • 2,046
  • 3
  • 22
  • 52
aped
  • 193
  • 1
  • 1
  • 8

6 Answers6

21

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]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
10

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]]
JBernardo
  • 32,262
  • 10
  • 90
  • 115
3

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
Muhammad Younus
  • 1,896
  • 19
  • 20
1

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)
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
0

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]
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
0

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]]]
Aleksey Vlasenko
  • 990
  • 9
  • 10