Reputation: 11
guys i m a beginner in python,i just observed one thing that when i generate a list from string using split(' ')[split elements by spaces] than operations(like sort) on that list give messed up results not as expected. plese tell me how i can overcome this problem? here is my code
str=raw_input() #suppose i give "50 100 50" as string
var=str.split(' ') #it splits into [50,100,50]
var.sort() #now sorting command
print "Sorted var is: %r" %var #it gives [100,50,50] instead of [50,50,100]
Upvotes: 1
Views: 49
Reputation: 13510
You have 3 issues here.
The first one, after you split the string you get a list of strings, which are then sorted alphabetically, where 100 indeed comes before 50!
So first you need to convert the list of strings to a list of integers, like this:
int_list = [int(x) for x in var]
or, my favorite if a function already exists:
int_list = map(int, var)
The second issue, not relating to the problem, but worth mentioning, is the line
str=raw_input()
Don't use str
as a variable name, because it is a type and a function and a class in Python, and by your assignment has overriden it.
And lastly, use
split('')
That is without any space, just an empty string. This way is treated specially in Python, to split on all kinds of spaces, like many spaces in a row, new lines, tabs etc... It is extremely useful to use it with an empty string argument.
Upvotes: 1
Reputation: 66
In variable var you have a string values and the code of char '1' less then code of char '5' and so on. It must be sorting by numeric values. You must convert values to int.
Try this code:
str=raw_input() #suppose i give "50 100 50" as string
var=str.split(' ') #it splits into [50,100,50]
#converting string to int
var = [int(num) for num in var]
var.sort() #now sorting command
print "Sorted var is: %r" %var
Upvotes: 0