0

I got 2D matrix of list with strings like:

somelist = [["12","10","0"]
            ["0","33","60"]]

And I need to convert all those str to int. My code so far is:

for i in somelist:
        for j in i:
            j = int(j)
PHA
  • 1,588
  • 5
  • 18
  • 37
Seba
  • 65
  • 2
  • 8
  • 4
    In you question "But isnt working" insufficently explains what doesn't "work". Please explain what happens when you execute the code and what you expected instead. – MadMike May 14 '18 at 12:10
  • 2
    @Jean-François Fabre mind adding https://stackoverflow.com/questions/2166577/casting-from-list-of-lists-of-strings-to-list-of-lists-of-ints-in-python to the list of duplicates? This one handles if the inputs were floating point. – user3483203 May 14 '18 at 12:38

3 Answers3

2
>>> [[int(i) for i in j] for j in somelist]
[[12, 10, 0], [0, 33, 60]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

or use map:

>>> [list(map(int, x)) for x in somelist]
[[12, 10, 0], [0, 33, 60]]

Here your fixed code:

somelist = [["12","10","0"],
            ["0","33","60"]]

for n, i in enumerate(somelist):
    for k, j in enumerate(i):
        somelist[n][k] = int(j)

print(somelist)

Output:

[[12, 10, 0], [0, 33, 60]]
Konstantin
  • 547
  • 4
  • 11
2

Your code doesn't work because int in Python is an immutable type. If I change an int variable, it will not change the value in its address, but it will change whole variable. So any list or object formerly holding it will not be changed. Here are some examples:

In [1]: a_list = [1,2,3]

In [2]: var = a_list[0]

In [3]: var
Out[3]: 1

In [4]: id(var)
Out[4]: 4465792624

In [5]: var = 30

In [6]: id(var) # A different address
Out[6]: 4465793552

In [7]: a_list
Out[7]: [1, 2, 3]

In [8]: id(a_list[0])
Out[8]: 4465792624

In [9]: a_list[0] = 30

In [10]: a_list
Out[10]: [30, 2, 3]

That's why if you do this slight change your code will work:

for i in somelist:
    for ind, j in enumerate(i):
        i[ind] = int(j)
Jundiaius
  • 6,214
  • 3
  • 30
  • 43