Skip to main content
 首页 » 编程设计

Python 列表频率

2025年05月04日12youxin

我必须弄清楚如何打印频率集。到目前为止,这是我的代码,但它一直跳过列表中的第一个数字。我想那是因为我以前从 data[0] 开始,但我不知道还有什么办法可以解决这个问题

def frequencies(data): 
 
    data.sort() 
 
    count = 0 
    previous = data[0] 
 
    print("data\tfrequency") # '\t' is the TAB character 
 
    for d in data: 
        if d == previous: 
            # same as the previous, so just increment the count 
            count += 1 
        else: 
            # we've found a new item so print out the old and reset the count 
            print(str(previous) + "\t" + str(count)) 
            count = 1 
 
        previous = d 

请您参考如下方法:

Python 自带一个内置的 Counter为您计算频率的类型。这并没有解决代码的原始问题,但它完成了您希望它做的事情。

>>> data = [1,2,3,4,2,2,3,5] 
>>> c = Counter(data) 
>>> c 
Counter({2: 3, 3: 2, 1: 1, 4: 1, 5: 1}) 
>>> for key in sorted(c.keys()): 
...     print('{}\t{}'.format(key, c[key])) 
... 
1   1 
2   3 
3   2 
4   1 
5   1