【问题标题】:Is there unexpected number result for Counter.most_commonCounter.most_common 是否有意外的数字结果
【发布时间】:2022-01-24 04:24:25
【问题描述】:
from collections import Counter

# Frequency table for a list of numbers
def frequency_table(numbers):
    table=Counter(numbers)
    for number in table.most_common():
        print('{0} \t {1}'.format(number[0],number[1]))
        
if __name__=='__main__':
    scores=[7,8,9,2,10,9,9,9,9,4,5,6,1,5,6,7,8,6,1,10]
    frequency_table(scores)

我运行这个后,2期变成了21,我试了很多次,我把结果放在下面

9 5
6 3
7 2
8 2
10 2
5 2
1 2
二十一
4 1

【问题讨论】:

  • 我无法使用您提供的代码重现此问题。它似乎按预期工作。
  • 你好,我试了很多次,只要列表中有2个,奇怪的结果就是21个。我以前从未遇到过这样的事情
  • 它工作正常。不过你可以加: in print('{0} :\t{1}'.format(number[0],number[1])),这样会更容易理解。

标签: python python-3.x collections counter


【解决方案1】:

您有一个整数列表,并从中创建计数器:

[7,8,9,2,10,9,9,9,9,4,5,6,1,5,6,7,8,6,1,10]

变成

Counter({7: 2, 8: 2, 9: 5, 2: 1, 10: 2, 4: 1, 5: 2, 6: 3, 1: 2})

which most_common items 是一个元组列表,其中元素是整数:

所以,我在输出中没有看到任何奇怪的东西。

[(9, 5), (6, 3), (7, 2), (8, 2), (10, 2), (5, 2), (1, 2), (2, 1), (4, 1)]

最常见的列表有9个元素,等于Counter的键、值对的个数。

在最常见的列表元组(2,1) 中存在

您可以将其打印为:

for x,y in Counter(scores).most_common():
    print(f"{x} {y}")

打印输出:

9 5
6 3
7 2
8 2
10 2
5 2
1 2
2 1
4 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多