Why is this happening with Python list.sort?

Based on the code:

a=['a','b','c','d']
b=a[::-1]
print b
c=zip(a,b)
print c
c.sort(key=lambda x:x[1])#
print c

He prints:

['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]

Why [('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')] change to [('' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ')' '


Similarly, given:

c.sort(key=lambda x:3)#
print c

He prints:

[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]

Nothing changes - why?

+3
source share
5 answers

because x [1] means the second

using

c.sort(key=lambda x:x[0])
+7
source

c, , , . ?!

+4
from operator import itemgetter    
c.sort(key=itemgetter(0))
+1

, [1] , .

, list.sort() stable, , , . .sort(reverse=True) .sort(), .reverse().

+1

, , , ( "a", "b", "c", "d" ). ?

0

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


All Articles