【问题标题】:Analyzing large amount of numbers using Python使用 Python 分析大量数字
【发布时间】:2020-04-17 16:39:30
【问题描述】:

我刚开始学习使用 Python 编程...

我需要在 Python 中分析大量随机数...准确地说是 108 000。

需要将它们放在一个列表中并计算数字出现的次数,它们在1-80范围内......

在我的情况下你会怎么做以及如何解决这个问题?

【问题讨论】:

    标签: python-3.x sorting random count numbers


    【解决方案1】:

    groupby 函数可以提供帮助。 https://docs.python.org/3/library/itertools.html#itertools.groupby

    >>> import itertools
    >>>
    >>> [(k, len(list(g)))  for k, g in itertools.groupby(sorted('cbcaaa'))]
    [('a', 3), ('b', 1), ('c', 2)]
    

    你可以用一堆 sorted 随机数做同样的事情。

    但是有更好的方法。

    由于您有很多输入值但可能的输出数量很少,请考虑分配 80 个计数器:

    from collections import defaultdict
    
    cnt = defaultdict(int)
    for num in random_nums:
        cnt[num] += 1
    

    【讨论】:

    • 首先,感谢您花时间回答我并帮助我,我会尝试的:)
    猜你喜欢
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2016-01-15
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2018-08-07
    相关资源
    最近更新 更多