Abhishek Abhishek
Abhishek Abhishek

Reputation: 87

converting values inside nested list into integers except first value

I have to convert values inside a nested list into integers except for the first value. For example:

x = [['a', '1',' 2',' 3', '4',' 5'], ['b', '11',' 12',' 13',' 14',' 15'], ['c', '21',' 22',' 23',' 24', '25']]

to this

x = [[ 1, 2, 3, 4, 5], [ 11, 12, 13, 14, 15], [21, 22, 23, 24, 25]]

I tried using

w = []
for i in list1:
    for j in i:
        v = list(int(j))
        w.append(v)

and

for i in file_list:
    j = i[:1] + list(map(int, i[1:]))

but I get

Traceback (most recent call last):   File  
"/Users/abhishekabhishek/PycharmProjects/normalize/venv/normalize.py",  
line 63, in <module>  
    v = list(int(j)) ValueError: invalid literal for int() with base 10: '2.66171813'

Upvotes: 0

Views: 56

Answers (2)

Chris
Chris

Reputation: 29742

Don't use int directly if your actual data contains float-like strs. Use float instead:

x = [['a', '1', ' 2.22', ' 3', '4', ' 5'],
 ['b', '11', ' 12', ' 13', ' 14', ' 15'],
 ['c', '21', ' 22', ' 23', ' 24', '25']]

new_list = [list(map(float, s[1:])) for s in x]
print(new_list)
[[1.0, 2.22, 3.0, 4.0, 5.0],
 [11.0, 12.0, 13.0, 14.0, 15.0],
 [21.0, 22.0, 23.0, 24.0, 25.0]]

In case there can be some empty str '':

x = [['a', '1', ' 2.22', ' 3', '4', ' 5'],
 ['b', '11', ' ', ' 13', ' 14', ' 15'],
 ['c', '21', ' 22', ' 23', ' 24', '25']]

new_list = [] 
for l in x:
    new_list.append([float(s) if s.strip() else None for s in l[1:]])
print(new_list)
[[1.0, 2.22, 3.0, 4.0, 5.0],
 [11.0, None, 13.0, 14.0, 15.0],
 [21.0, 22.0, 23.0, 24.0, 25.0]]

Upvotes: 1

blhsing
blhsing

Reputation: 106523

A more robust way to check if a string can be converted to a number is to actually convert it, but use a try-except block to catch exceptions:

for i, l in enumerate(x):
    r = []
    for f in l:
        try:
            r.append(float(f))
        except ValueError:
            pass
    x[i] = r

so that given:

x = [['a', '1.1',' 2',' 3', '4',' 5'], ['b', '11',' 12',' 13',' 14',' 15'], ['c', '21',' 22',' 23',' 24', '25']]

x would become:

[[1.1, 2.0, 3.0, 4.0, 5.0], [11.0, 12.0, 13.0, 14.0, 15.0], [21.0, 22.0, 23.0, 24.0, 25.0]]

Upvotes: 1

Related Questions