gpt4 book ai didi

python - 按字典的值降序和键升序对字典进行排序

转载 作者:行者123 更新时间:2023-12-03 02:42:50 29 4
gpt4 key购买 nike

我的任务是提取字符串中的所有唯一字符(不包括空格),并根据字符串中给定字符的出现次数对其进行排序(因此按降序排序),如果存在平局,则按他们的 ASCII 代码。

示例:

Input: 'I am a cat'

Output: 'aIcmt'

我面临的问题特别是如果我使用这行代码进行排序:

char_list = Sorted(char_dict.items(), key = lambda x: (x[1],ord(x[0])), reverse = True)

它甚至对对字典的 char 部分进行排序的 ord(x[0]) 进行反向排序,尽管我只想对字符出现的值进行排序.

这是我的引用代码:

string_list = [char for char in string]
string_list = [char for char in string_list if char != ' ']

print(string_list)

char_dict = {}

for char in string_list:
if char not in char_dict:
char_dict[char] = 0
else:
char_dict[char] += 1

char_list = sorted(char_dict.items(), key = lambda x: (x[1],ord(x[0])), reverse = True)
print(char_list)

for i in char_list:
print(i[0], end = '')


最佳答案

您可以尝试组合使用Countersortedjoin

from collections import Counter

input_str = 'I am a cat'

# use counter to get count of each character including white space
t = list(Counter(input_str).most_common())

# sort on count on reverse and ascii on ascending when ties
t = sorted(t, key=lambda i: (-i[1], i[0]))

# exclude white space and join remaining sorted characters
res = ''.join(i[0] for i in t if i[0] != ' ')

print(res)

输出:

aIcmt

关于python - 按字典的值降序和键升序对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59062818/

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