I have a list as follows:
pos = ['52.1,13.3','53.2,14.3',....,'55.3,16.4']
I want to change each string in the list to a float, such that I get the following:
pos = [52.1,13.3,53.2,14.3,....,55.3,16.4]
I am using the following loop:
b = []
for str in a:
str = float(str)
b.append(str)
print (b)
Which raises the following error
ValueError: could not convert string to float: '52.1,13.3'
How do I change the strings into separate floats in a new list?
CodePudding user response:
You have to split the strings at the comma and apply float
to each of the entries. Then extend the list with those floating point values.
pos = ['52.1,13.3','53.2,14.3','55.3,16.4']
lst = []
for entry in pos:
lst.extend(map(float, entry.split(',')))
print(lst)
This will give you [52.1, 13.3, 53.2, 14.3, 55.3, 16.4]
.
If you're unfamiliar with map
you should learn how to use it. But nevertheless here's a version with a loop approach:
lst = []
for entry in pos:
for value in entry.split(','):
lst.append(float(value))
print(lst)