如何按值对字典进行排序并返回格式化字符串列表?
我有一个字典:
text_to_count = { "text1": 1, "text2":0, "text3":2}
我想通过对该字典的值进行排序(按降序排列)来创建格式化字符串的列表。
即,我喜欢以下列表:
result = ["2 - text3", "1 - text1", "0 - text2"]
有什么想法吗?
编辑:
在等待回复的同时,我不断地研究它并想出了:
result = map(lambda x: "{!s} - {!s}".format(x[1], x[0]),
sorted(text_to_count.iteritems(),
key = lambda(k, v): (v, k), reverse=True ))
虽然我仍然有兴趣看看还有什么其他解决方案,可能是更好的解决方案。
I've got a dict:
text_to_count = { "text1": 1, "text2":0, "text3":2}
I'd like to create a list of formatted strings by sorting this dict's values (in descending order).
I.e., I like following list:
result = ["2 - text3", "1 - text1", "0 - text2"]
Any ideas?
Edit:
While waiting for responses, I kept hacking at it and came up with:
result = map(lambda x: "{!s} - {!s}".format(x[1], x[0]),
sorted(text_to_count.iteritems(),
key = lambda(k, v): (v, k), reverse=True ))
Tho I'm still interested in seeing what other solutions there are, possibly one better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这怎么样?
How's this?
还有一种,代码高尔夫风格:
PS。为了说明 Ignacio Vazquez-Abrams 评论提出的观点,请注意如果存在值重复,排序结果会如何变化:
['1 - txt3', '1 - txt1 ', '0 - txt2']
['1 - txt1', '1 - txt3', '0 - txt2']
And one more, codegolf style:
PS. to illustrate a point brought by Ignacio Vazquez-Abrams comment, note how the sorts results can vary if there are value repeats:
['1 - txt3', '1 - txt1', '0 - txt2']
['1 - txt1', '1 - txt3', '0 - txt2']