Bunny Rabbit
Bunny Rabbit

Reputation: 8411

Why am I not getting the result of sorted function in expected order?

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

Answers (5)

John Machin
John Machin

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

Platinum Azure
Platinum Azure

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

Donald Miner
Donald Miner

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

millimoose
millimoose

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

jro
jro

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

Related Questions