Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this sorting code working?

Tags:

python

How is this sorting code working? I cannot understand how the values returned by the iterator are being used to sort the list?

mylist=["zero","two","one"]
list1=[3,1,2]
it = iter(list1)
sorted(mylist, key=lambda x: next(it))

Output:

['two', 'one', 'zero']
like image 702
Ankur Agarwal Avatar asked Sep 08 '13 22:09

Ankur Agarwal


2 Answers

It works like this - the key=lambda x: next(it) part is stating: assign an order value of 3, then 1 then 2 to each of the elements in mylist. So two comes first, then one then zero:

["zero", "two", "one"] # original list
[  3,      1,     2  ] # assign this order to each element

Now, after sorting:

[  1,     2,      3  ] # sorted keys
["two", "one", "zero"] # and there you go!
like image 129
Óscar López Avatar answered Sep 22 '22 19:09

Óscar López


next(it) returns next item of the iterable every time it's called:

>>> list1=[3,1,2]
>>> it = iter(list1)
>>> print next(it)
3
>>> print next(it)
1
>>> print next(it)
2

key is a function that is called on each list element for making comparisons.

sorted(): If you don't specify key parameter it will compare item values, if you provide key - it uses the result of key function calls for making comparisons between items of the list.

So, for "zero" it is 3, for "two" - 1, for "one" - 2. Since 1 < 2 < 3, the result is ["two", "one", "zero"].

like image 31
alecxe Avatar answered Sep 25 '22 19:09

alecxe