gpt4 book ai didi

python - 根据计数器值对列表进行排序

转载 作者:行者123 更新时间:2023-12-01 02:00:21 25 4
gpt4 key购买 nike

如何根据 Counter 对象的值对 Python 列表进行排序?

c = Counter({"a": 1, "b": 6, "c":19})
l = ["b", "c", "a"]

# after sorting based on counter values
l = ["c", "b", "a"]

最佳答案

sorted()采用如下关键函数:

代码:

sorted(l, key=lambda x: -c[x])

或就地为:

l.sort(key=lambda x: -c[x])

测试代码:

from collections import Counter

c = Counter({"a": 1, "b": 6, "c": 19})
l = ["b", "c", "a"]

# after sorting based on counter values
l = ["c", "b", "a"]

print(sorted(l, key=lambda x: -c[x]))

结果:

['c', 'b', 'a']

关于python - 根据计数器值对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723836/

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