gpt4 book ai didi

python - 如何使用 sorted() 方法对成对列表进行排序?

转载 作者:行者123 更新时间:2023-11-28 21:13:48 26 4
gpt4 key购买 nike

Define a function, histo(s) computing the histogram of a given string. Characters must appear in the list ordered from least frequent to most frequent. For example, histo('implemented') is [('t', 1), ('p', 1), ('n', 1), ('l', 1), ('i', 1), ('d', 1), ('m',
2), ('e', 3)]
. (Characters with the same frequency must appear in decreasing alphabetical order.) To implement the sorting, use the python built-in function sorted.

这是我的作品:

def keyf(p):
x,y = p
return (y,x)

s = "implemented"
d = {}
for c in s:
d[c] = d.get(c, 0) + 1
dlist = list(d.items())
dlist = sorted(dlist, key = keyf, reverse = False)

在我运行之后,dlist 是 [('d', 1), ('i', 1), ('l', 1), ('n', 1), ('p ', 1), ('t', 1), ('m', 2), ('e', 3)]。问题是具有相同频率的对中的第一个元素不是按降序排列的,我该如何解决这个问题?我试着把

dlist = sorted(dlist, reverse = True)

最后,还是不行。

最佳答案

可以在键函数中反转字符的顺序:

def keyf(p):
x,y = p
return (y,-ord(x))

关于python - 如何使用 sorted() 方法对成对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32436988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com