Reputation: 339
I'm trying to write a code that takes an input of floating numbers from a user, sort the values in ascending order. I tried a options found in Stack Overflow, but its still not working. This is a piece of my code:
if option == 'f':
x = input()
y = (sorted(x, key=lambda z: float(z))) # sort float ascending
print(y)
.
>>> Input: 5.0 , 4.9 , 3.1, 0.5
Output: 0.5, 3.1, 4.9, 5.0
How can i get list of floating point numbers and print the sorted output?
Upvotes: 0
Views: 1651
Reputation: 87084
You need to split the input string into separate floating point number strings, then sort on their float value. The following code splits on commas and removes any whitespace before sorting:
if option == 'f':
x = (s.strip() for s in input().split(','))
y = (sorted(x, key=lambda z: float(z))) # sort float ascending
print(y)
This outputs:
['0.5', '3.1', '4.9', '5.0']
You can also print it like this:
>>> print(', '.join(y)) # using join()
0.5, 3.1, 4.9, 5.0
>>> print(*y, sep=', ') # Python 3 style print function
0.5, 3.1, 4.9, 5.0
Upvotes: 3
Reputation: 139
Your input is a string of type str
. You should split it and convert to float
.
@mhawke gives a good example.
Upvotes: 0