converting each element from string to int in nest

2019-03-02 11:13发布

问题:

This question already has an answer here:

  • How to convert strings into integers in Python? 14 answers

I have data in python with nested lists, a part of which looks like:

data = [['214', '205', '0', '14', '710', '1813494849', '0'], ['214', '204', '0', '30', '710', '1813494856', '0'], ['214', '204', '0', '34', '710', '1813494863', '0'], ['213', '204', '0', '35', '710', '1813494870', '0'], ['213', '203', '0', '35', '710', '1813494877', '0']]

While converting the data using couple methods:

1.

 new_data_list = [[int(x) for x in list] for list in data]
  1. list=[]
    for i in range(0,len(data)):
        list.append([])
        for j in range(0,len(data[i])):
            b=int(data[i][j])
            list[i].append(b)
    

    I am getting the error which says:

ValueError: invalid literal for int() with base 10: ''

There are no non-numeric data in my list of data. But there might be something with the header, like an empty header treated as non-numeric value as I have created a list of data from csv.

I wanted to know an efficient way which can convert each element of the list to int while keeping the data multi list.

回答1:

Call int for each item in each nested list:

new_list = [[int(x) for x in lst] for lst in nested]

Or using map:

new_list = [list(map(int, lst)) for lst in nested]


回答2:

A concise one is:

x = ['123', '12', '5']
r = list(map(int, x))
print x
>x = [123, 12, 5]