I want to use list comprehension to change an element within a nested list to float.
lines = [[1, '74.37000326528938', 'Psychologist'], [2, '67.49686206937491', 'Psychologist'], [3, '74.92356434760966', 'Psychologist']]
>>> lines = [[line[0]] + [float(x) for x in line[1]] + [line[2]] for line in lines]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: .
I also don't understand why this would work for a different example:
mylist = [['1','2','3'],['5','6','7']]
datl3 = [[int(x) for x in line[0]] + line[1:] for line in mylist]
datl4 = [[line[0]] + [float(x) for x in line[1]] + [line[2]] for line in datl3]
>>> datl4
[[1, 2.0, '3'], [5, 6.0, '7']]
I think it has to do with decimal points, because the code won't work for this example:
mylist = [['1','2.555','3'],['5','6.777','7']]
datl3 = [[int(x) for x in line[0]] + line[1:] for line in mylist]
datl4 = [[line[0]] + [float(x) for x in line[1]] + [line[2]] for line in datl3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: .
for l in lines: l[1] = float(l[1])work?lis a reference to an inner list, it ends up modifying the originallines.