如何按值对字典进行排序并返回格式化字符串列表?

发布于 2024-10-14 17:55:55 字数 555 浏览 1 评论 0原文

我有一个字典:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眼睛会笑 2024-10-21 17:55:55
['%d - %s' % (v, k) for (k, v) in sorted(text_to_count.iteritems(),
    key=operator.itemgetter(1), reverse=True)]
['%d - %s' % (v, k) for (k, v) in sorted(text_to_count.iteritems(),
    key=operator.itemgetter(1), reverse=True)]
哑剧 2024-10-21 17:55:55

这怎么样?

result = ['{1} - {0}'.format(*pair) for pair in sorted(text_to_count.iteritems(), key = lambda (_,v): v, reverse = True)]

How's this?

result = ['{1} - {0}'.format(*pair) for pair in sorted(text_to_count.iteritems(), key = lambda (_,v): v, reverse = True)]
倾城月光淡如水﹏ 2024-10-21 17:55:55

还有一种,代码高尔夫风格:

>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get)[::-1]]
['2 - text3', '1 - text1', '0 - text2']

PS。为了说明 Ignacio Vazquez-Abrams 评论提出的观点,请注意如果存在值重复,排序结果会如何变化:

>>> t={'txt1':1, 'txt2':0, 'txt3':1}
>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get)[::-1]]

['1 - txt3', '1 - txt1 ', '0 - txt2']

>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get,reverse=True)]

['1 - txt1', '1 - txt3', '0 - txt2']

And one more, codegolf style:

>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get)[::-1]]
['2 - text3', '1 - text1', '0 - text2']

PS. to illustrate a point brought by Ignacio Vazquez-Abrams comment, note how the sorts results can vary if there are value repeats:

>>> t={'txt1':1, 'txt2':0, 'txt3':1}
>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get)[::-1]]

['1 - txt3', '1 - txt1', '0 - txt2']

>>> ['%s - %s'%(t[x],x) for x in sorted(t,key=t.get,reverse=True)]

['1 - txt1', '1 - txt3', '0 - txt2']

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文