Reputation: 8411
print activities
activities = sorted(activities,key = lambda item:item[1])
print activities
Activities in this case is a list of tuples like (start_number,finish_number)
the output of the above code according to me should be the list of values sorted according the the increasing order of finish_number
. When I tried the above code in shell I got the following output. I am not sure why the second list is not sorted according the the increasing order of the finish_number
. Please help me in understanding this.
[('1', '4'), ('3', '5'), ('0', '6'), ('5', '7'), ('3', '9'), ('5', '9'), ('6', '10'), ('8', '11'), ('8', '12'), ('2', '14'), ('12', '16')]
[('6', '10'), ('8', '11'), ('8', '12'), ('2', '14'), ('12', '16'), ('1', '4'), ('3', '5'), ('0', '6'), ('5', '7'), ('3', '9'), ('5', '9')]
Upvotes: 0
Views: 104
Reputation: 82924
Look for a BROADER solution to your problem: Convert your data from str
to int
immediately on input, work with it as int
(otherwise you'll be continually be bumping into little problems like this), and format your data as str
for output.
This principle applies generally, e.g. when working with non-ASCII string data, do UTF-8 -> unicode -> UTF-8; don't try to manipulate undecoded text.
Upvotes: 1
Reputation: 46183
Your items are being compared as strings, not as numbers. Thus, since the 1
character comes before 4
lexicographically, it makes sense that 10
comes before 4
.
You need to cast the value to an int first:
activities = sorted(activities,key = lambda item:int(item[1]))
Upvotes: 6
Reputation: 39893
You are sorting strings, not numbers. Strings get sorted character by character.
So, for example '40'
is greater than '100'
because character 4
is larger than 1
.
You can fix this on the fly by simply casting the item as an integer.
activities = sorted(activities,key = lambda item: int(item[1]))
Upvotes: 2
Reputation: 39950
It's because you're not storing the number as a number, but as a string. The string '10'
comes before the string '2'
. Try:
activities = sorted(activities, key=lambda i: int(i[1]))
Upvotes: 1
Reputation: 9474
You are sorting strings instead of integers: in that case, 10
is "smaller" than 4
. To sort on integers, convert it to this:
activites = sorted(activities,key = lambda item:int(item[1]))
print activities
Results in:
[('1', '4'), ('3', '5'), ('0', '6'), ('5', '7'), ('3', '9'), ('5', '9'), ('6', '10'), ('8', '11'), ('8', '12'), ('2', '14'), ('12', '16')]
Upvotes: 6