Issue
I am trying to get a list input by the user and then sort the list elements (which are integers) in ascending order. But the elements are stored as strings and I don't know how to convert each element into int
type. For example:
p = input("Enter comma separated numbers:")
p = p.split(",")
p.sort()
print(p)
When I input
-9,-3,-1,-100,-4
I get the result as:
['-1', '-100', '-3', '-4', '-9']
But the desired output is:
[-100, -9, -4, -3, -1]
Solution
Your p
is a list that consists of strings therefore they won't be sorted by their numerical values. Try this:
p.sort(key=int)
If you need a list of integers, convert them in the beginning:
p = [int(i) for i in p.split(",")]
Answered By - Selcuk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.