gpt4 book ai didi

collections - 以降序遍历 collections.Counter() 实例的 Pythonic 方式?

转载 作者:IT老高 更新时间:2023-10-28 22:15:03 27 4
gpt4 key购买 nike

在 Python 2.7 中,我想以递减计数顺序迭代 collections.Counter 实例。

>>> import collections
>>> c = collections.Counter()
>>> c['a'] = 1
>>> c['b'] = 999
>>> c
Counter({'b': 999, 'a': 1})
>>> for x in c:
print x
a
b

在上面的示例中,元素似乎按照它们添加到 Counter 实例的顺序进行迭代。

我想从最高到最低遍历列表。我看到 Counter 的字符串表示是这样做的,只是想知道是否有推荐的方法。

最佳答案

您可以遍历 c.most_common() 以按所需顺序获取项目。另见documentation of Counter.most_common() .

例子:

>>> c = collections.Counter(a=1, b=999)
>>> c.most_common()
[('b', 999), ('a', 1)]

关于collections - 以降序遍历 collections.Counter() 实例的 Pythonic 方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11037005/

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