Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting each element from string to int in nested list in python [duplicate]

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.

like image 982
The Novice Programmer Avatar asked Nov 26 '17 07:11

The Novice Programmer


1 Answers

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]
like image 172
janos Avatar answered Nov 06 '22 15:11

janos