+ 1

key = lambda...... usage?

Hi everyone, Can someone explain why the below code don't output like that >> [1, 2, 3, 4, 5]. a_list = [3, -4, -2, 5, 1] f = sorted(a_list, key = lambda x: abs(x)) print(f) output >> [1, -2, 3, -4, 5] Thanks in advance.

5th Jul 2018, 2:09 PM
Servet Birlik
Servet Birlik - avatar
3 odpowiedzi
+ 2
Let we have a number which is n.abs is a function which gives you distance from 0 to n. now in your code it sort the number acc. to abs function.so 3 has distance from zero is 3. -4 has distance from zero is 4 -2 has distance from zero is 2 5 has distance from zero is 5 1 has distance from zero is 1 Now,abs function include the number in list in increasing order of their distance from zero. 1 has first because it distance from zero is 1. -2 is second because it has distance from zero is 2. blablabla...... so that's why your output is 1, -2, 3, -4, 5
5th Jul 2018, 4:30 PM
Maninder $ingh
Maninder $ingh - avatar
+ 1
The lambda in the key is only used to determine the position in the sort, it does not change the value. What you want is a_list=[1,-2,-5,4,-3] f=sorted(map(abs,a_list)) print(f)
5th Jul 2018, 4:27 PM
Louis
Louis - avatar
0
hi, it is working correctly. sorted method sorts list using abs method but do not change the list elements. you can directly pass abs also. #sorte a list using abs method l = [-4,-5,1,2,3,6] print(sorted(l,key=abs)) #sort a list of string using last character l = ['jaz','dixit','dipak','jaimin','jay'] print(sorted(l,key=(lambda x: x[-1])))
5th Jul 2018, 4:19 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar