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]
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With