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)
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)
>>> [[int(i) for i in j] for j in somelist]
[[12, 10, 0], [0, 33, 60]]
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]]
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)