Posts: 404
Threads: 94
Joined: Dec 2017
Dec-09-2017, 10:32 PM
(This post was last modified: Dec-09-2017, 10:32 PM by Truman.)
I'm reading python tutorial and as an example of use of lambda there is this code:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) I do not understand this code, hope that somebody can explain me the logic behind the output:
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Posts: 544
Threads: 15
Joined: Oct 2016
Dec-09-2017, 11:09 PM
(This post was last modified: Dec-09-2017, 11:09 PM by Windspar.)
lambda are simple functions
code equal to
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
def pair_sort(pair):
return pair[1] # this point to second object in list (1, 'one')[1] == 'one'
pairs.sort(key=pair_sort)
print(pairs)
99 percent of computer problems exists between chair and keyboard.
Posts: 2,953
Threads: 48
Joined: Sep 2016
lambda pair: pair[1] lambda is called an anonymous function. The argument is passed before the ":". The expression which returns some value is after the colons. In this case, this is pair[1] which points to the second element of an iterable. So the list will be sorted by the second element of the tuples.
Posts: 404
Threads: 94
Joined: Dec 2017
(Dec-10-2017, 06:33 AM)wavic Wrote: lambda pair: pair[1] lambda is called an anonymous function. The argument is passed before the ":". The expression which returns some value is after the colons. In this case, this is pair[1] which points to the second element of an iterable. So the list will be sorted by the second element of the tuples.
The second element of the iterable is "(2, 'two')"? Unfortunately, I still don't understand this order 4-1-3-2.
Posts: 103
Threads: 15
Joined: Nov 2017
(1, 'one')
(2, 'two')
(3, 'three')
(4, 'four') The second element of all the tuple is
'one'
'two'
'three'
'four' if you sort the above words, it would come out as
(4, 'four'),
(1, 'one'),
(3, 'three'),
(2, 'two')
Posts: 1,150
Threads: 42
Joined: Sep 2016
As wavic said, list is sorted by second element of the tuples. In your list (iterable) they are strings. Strings are ordered lexically, so "four" is first one, as "f" appears in alphabet before the rest of the initials of other values ("one", "two" and "three").
Posts: 404
Threads: 94
Joined: Dec 2017
(Dec-10-2017, 04:54 PM)j.crater Wrote: As wavic said, list is sorted by second element of the tuples. In your list (iterable) they are strings. Strings are ordered lexically, so "four" is first one, as "f" appears in alphabet before the rest of the initials of other values ("one", "two" and "three").
This is what completely missed.
Thank you all.
|