How does this sort code work?

How does this sort code work? I can’t understand how the values ​​returned by the iterator are 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'] 
+6
source share
2 answers

It works like this: the key=lambda x: next(it) indicates: assign a value of order 3 , then 1 , then 2 for each of the elements in mylist . So, first two , 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! 
+7
source

next(it) returns the next iteration element each time it calls:

 >>> 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 for each list item for comparison.

sorted() : If you do not specify the key parameter, it compares the values ​​of the element; if you provide the key , it uses the result of calls to key functions to compare between the elements 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"] .

+1
source

Source: https://habr.com/ru/post/953447/


All Articles