我有一本字典:
{ 'a': 6, 'b': 1, 'c': 2 }
Run Code Online (Sandbox Code Playgroud)
我想按价值迭代它,而不是按键.换一种说法:
(b, 1)
(c, 2)
(a, 6)
Run Code Online (Sandbox Code Playgroud)
什么是最直接的方式?
var*_*tec 38
sorted(dictionary.items(), key=lambda x: x[1])
Run Code Online (Sandbox Code Playgroud)
对于那些讨厌lambda的人:-)
import operator
sorted(dictionary.items(), key=operator.itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
但是operator版本需要CPython 2.5+
对于非Python 3程序,您将需要使用iteritems来提高生成器的性能,这样可以一次生成一个值,而不是一次返回所有生成器.
sorted(d.iteritems(), key=lambda x: x[1])
Run Code Online (Sandbox Code Playgroud)
对于更大的字典,我们可以更进一步,将关键函数放在C而不是Python中,就像现在使用lambda一样.
import operator
sorted(d.iteritems(), key=operator.itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
万岁!
It can often be very handy to use namedtuple. For example, you have a dictionary of name and score and you want to sort on 'score':
import collections
Player = collections.namedtuple('Player', 'score name')
d = {'John':5, 'Alex':10, 'Richard': 7}
Run Code Online (Sandbox Code Playgroud)
sorting with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
Run Code Online (Sandbox Code Playgroud)
sorting with highest score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
Run Code Online (Sandbox Code Playgroud)
The order of 'key' and 'value' in the listed tuples is (value, key), but now you can get the name and score of, let's say the second-best player (index=1) very Pythonically like this:
player = best[1]
player.name
'Richard'
player.score
7
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20206 次 |
| 最近记录: |