Reputation: 25
I'm trying to make a program in Python 3 where user gives multiple values in one input separated by space and these values are added to a list in form of a list, thus creating a list of lists. But I just cant convert these values to float.
This is the "base" of the code:
lst = []
ln = input()
values = ln.split(" ")
lst.extend([values])
while ln != "":
ln = input()
values = ln.split(" ")
lst.extend([values])
Which would give me list like this
[['1', '2'], ['3', '4']]
So the problem is that I cannot convert these strings to floats. One of the ways I've tried is
for i in lst:
for j in i:
j = float(j)
Which just gives me "ValueError: could not convert string to float:"
. I've also tried mapping but that doesn't work either.
Upvotes: 1
Views: 7904
Reputation: 78680
The most straight forward approach is to convert the strings in your sub-lists to floats before appending the sub-lists to your final list. That means use
values = list(map(float, ln.split(" ")))
Alternatively, you can post-process your list of lists like this:
>>> lst = [['1', '2', '3'], ['4', '5', '6']]
>>> lst = [list(map(float, sublist)) for sublist in lst]
>>> lst
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
... which also has a nested list-comprehension version:
>>> [[float(x) for x in sublist] for sublist in lst]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
... which if you are new to Python might want to write as
>>> lst = [['1', '2', '3'], ['4', '5', '6']]
>>> result = []
>>>
>>> for sublist in lst:
... float_sublist = []
... for x in sublist:
... float_sublist.append(float(x))
... result.append(float_sublist)
...
>>> result
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
In addition, but unrelated, use lst.append(values)
instead of lst.extend([values])
. The effect is the same, but the latter one looks weird and goes against the intended use-case for extend
- appending objects from an iterable one by one, which you suppress by wrapping your iterable values
in another iterable by passing [values]
.
Upvotes: 5
Reputation: 6348
Python has less than intuitive ways to modify primitive objects within a list- many times the easiest way to get around that is to create a new list:
lst = [['1', '2'], ['3', '4']]
floatlist = []
for l in lst:
floatlist.append([float(i) for i in l])
print(floatlist)
Upvotes: 1