gpt4 book ai didi

python - 通过在 python 中对字典进行排序来提取键列表

转载 作者:行者123 更新时间:2023-11-30 21:59:22 24 4
gpt4 key购买 nike

我的程序输出为 python 字典,我想要来自 dictn 的键列表:

s = "cool_ice_wifi"
r = ["water_is_cool", "cold_ice_drink", "cool_wifi_speed"]
good_list=s.split("_")
dictn={}
for i in range(len(r)):
split_review=r[i].split("_")
counter=0
for good_word in good_list:
if good_word in split_review:
counter=counter+1
d1={i:counter}
dictn.update(d1)

print(dictn)

我们应该获得 key 的条件:

  1. 具有相同值的键将复制索引,就像在虚拟列表中一样。
  2. 值最高的键将首先出现,然后是虚拟列表中值最低的键

字典={0: 1, 1: 1, 2: 2}

预期输出 = [2,0,1]

最佳答案

您可以使用列表组合:

[key for key in sorted(dictn, key=dictn.get, reverse=True)]

关于python - 通过在 python 中对字典进行排序来提取键列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610222/

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