开发者

Why does this happen with Python's list.sort?

Given 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

It prints:

['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 开发者_Python百科'c'), ('a', 'd')]

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


Similarly, given:

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

It prints:

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

Nothing changes - why?


because x[1] means second

use

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


You've sorted c using the second item as the key, and the second item does indeed go up, just as you asked for it to go up. What's so surprising?!


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


As the others have said, [1] refers to the second element, so the elements in the first part are sorted that way.

As for the second part, list.sort() is stable, so elements that evaluate to the same key will maintain their relative position in the sequence. This is why using .sort(reverse=True) can give different results from .sort() followed by .reverse().


You've sorted the list using the second element of each tuple as a key so you get the tuples ordered by their second element (Notice the 'a', 'b', 'c', 'd' in increasing order). What's the problem?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜