在列表中查找数字的频率

时间:2018-12-09 01:04:15

标签: python

from collections import Counter
f = open('input.txt')
lines = f.readlines()
counter = 0
freq = []
for line in lines:
    conv_int = int(line)
    counter = counter + conv_int
    freq.append(counter)
for i in freq:
    print(Counter(freq))
print(counter)

此代码循环遍历带有各种负数和正数的文本文件,并将它们从零开始加在一起。但是我想知道如何查找每个数字在此文件中出现多少次?

2 个答案:

答案 0 :(得分:1)

Collection's Counter希望将Iterable作为参数而不是项目:

import collections

with open('input.txt', 'r') as input_file:
    numbers = [int(line) for line in input_file]
    numbers_sum = sum(numbers)
    numbers_frequency = collections.Counter(numbers)

但是,如果效率对您而言不成问题,而您只是想sum文件中的所有数字及其count的频率,则无需导入库就可以了

with open('input.txt', 'r') as input_file:
    numbers = [int(line) for line in input_file]
    numbers_sum = sum(numbers)
    numbers_frequency = {n: numbers.count(n) for n in set(numbers)}

答案 1 :(得分:0)

您的文件的每一行都有一个整数,您想要每个整数的总和和频率,对吗?试试这个。

from collections import Counter
with open("input.txt", "rt") as f:
    total = 0
    count = Counter()
    for line in f:
        conv_int = int(line)
        total += conv_int
        count[conv_int] += 1
    print(count)
    print(total)