Utkarsh Utkarsh - 2 months ago 6
Python Question

How to convert a string list to integer in python?

I have the following list of values:

DATA = [['5', '1'], ['5', '5'], ['3', '1'], ['6', '1'], ['4', '3']]


How can I convert it to :

DATA = [[5, 1], [5, 5], [3, 1], [6, 1], [4, 3]]


Note : I have already tried the following but all are not working in Python 3 :

1. DATA = [int(i) for i in DATA]
2. DATA = list(list(int(a) for a in b) for b in DA if a.isdigit())
3. DATA = [map(int,x) for x in DATA]


Please help me with this. Thanks!!

Answer

Your third one is actually correct. In Python 3 map returns a map object, so you just have to call list on it to get a list.

DATA =  [['5', '1'], ['5', '5'], ['3', '1'], ['6', '1'], ['4', '3']]

d = [list(map(int, x)) for x in DATA]

# Output:
# [[5, 1], [5, 5], [3, 1], [6, 1], [4, 3]]

# type of one of the items in the sublist
# print(type(d[0][0])
# <class 'int'>
Comments