Python中的频率

2024-05-19 12:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

所以我有这个频率代码,但每次都会把列表中的最后一个数字去掉

这可能与我从上一个开始的位置有关,也可能与我在最后将上一个重置为d的位置有关


Tags: thefordatasoisdefcountsort
2条回答

对于最后一组元素,您永远不会将它们打印出来,因为在打印之后您永远不会发现不同的内容。你需要在循环后重复打印输出

但这是相当学术的;在现实世界中,您更有可能使用Counter

from collections import Counter
counter = Counter(data)
for key in counter:
    print("%s\t%d" % (key, counter[key]))

可以使用count对列表/序列中的项进行计数。因此,您的代码可以简化为:

def frequencies(data):
    unique_items = set(data)
    for item in unique_items:
        print('%s\t%s' % (item, data.count(item)))

相关问题 更多 >