在Python中按字典的值按降序对其排序,其键按升序对字典进行排序 - python

我的任务是提取字符串中的所有唯一字符(不包括空格),然后根据字符串中给定字符的出现量对它进行排序(以降序排列),如果是领带,则按其ASCII码排序。
例:

输入:“我是猫”
输出:“ aIcmt”

我特别面临的问题是,如果我使用以下代码行进行排序:
char_list = sorted(char_dict.items(), key = lambda x: (x[1],ord(x[0])), reverse = True)
即使我只想对字符出现的值进行排序,它甚至对对字典的ord(x[0])部分进行排序的char进行反向排序。
这是我的参考代码:

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

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…