4

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]]
srky
  • 350
  • 2
  • 4
  • 12

3 Answers3

11

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]]
Transhuman
  • 3,527
  • 1
  • 9
  • 15
5

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]]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • 1
    this is Python 2 only. Cast to `list` to be cross-version – Ma0 Jul 03 '17 at 12:10
  • @Ev.Kounis OP doesn't mentioned any version. And the functionality part will work with both. – Rahul K P Jul 03 '17 at 12:11
  • Whenever 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. – Ma0 Jul 03 '17 at 12:13
  • @Ev.Kounis So i used `2.7` here. I guess it's pretty stable and safest. – Rahul K P Jul 03 '17 at 12:14
0

Python has a function called int() that will make strings into integers. Try that out.

Steve Woods
  • 227
  • 1
  • 9