How to convert 2D string list to 2D int list python?
10,097
Solution 1
Python 3.x
print ( [list( map(int,i) ) for i in l] )
Output :
[[1, 1, 3], [2, 3, 5], [3], [4, 5], [5, 1], [6, 6], [7]]
Solution 2
Do with list comprehension,
In [24]: l = [['1', ' 1', ' 3'], ['2', ' 3', ' 5'], ['3'], ['4', ' 5'], ['5', ' 1'], ['6', ' 6'], ['7']]
In [25]: result = [map(int,i) for i in l]
Result
In [26]: print result
[[1, 1, 3], [2, 3, 5], [3], [4, 5], [5, 1], [6, 6], [7]]
Author by
srky
Updated on June 26, 2022Comments
-
srky almost 2 years
How to convert a 2d string list in 2d int list? example:
>>> pin_configuration = [['1', ' 1', ' 3'], ['2', ' 3', ' 5'], ['3'], ['4', ' 5'], ['5', ' 1'], ['6', ' 6'], ['7']] >>> to [[1,1,3], [2,3,5], [3], [4,5], [5,1], [6,6], [7]]
-
Ma0 almost 7 yearsthis is Python 2 only. Cast to
list
to be cross-version -
Rahul K P almost 7 years@Ev.Kounis OP doesn't mentioned any version. And the functionality part will work with both.
-
Ma0 almost 7 yearsWhenever no version is mentioned and one has to be assumed, going with the latest is the safest bet imho. But covering both is rather trivial in this case.
-
Rahul K P almost 7 years@Ev.Kounis So i used
2.7
here. I guess it's pretty stable and safest.