简体   繁体   中英

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!!

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'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM