Python - 如何逐行计数Counter

时间:2017-07-28 17:02:07

标签: python counter

我有以下代码打开一个包含逗号分隔数字的文本文件。

from collections import Counter

with open("lottoresults.txt") as inf:
    all_lines = [inf.read()]
    print(all_lines)
    for each_line in all_lines:
        print(each_line)
        counts = Counter(each_line)
        set = each_line.replace("", "").split()
        print(set)
        for numbers in set:
            nums = [int(i) for i in numbers.replace(",", "\n").split()]
            print(nums)
            for number in nums:
                counts = Counter(nums)
print(counts)

结果是:

['1,2,3,4,5\n1,3,5,6,7\n1,8,9,10,11']
1,2,3,4,5
1,3,5,6,7
1,8,9,10,11
['1,2,3,4,5', '1,3,5,6,7', '1,8,9,10,11']
[1, 2, 3, 4, 5]
[1, 3, 5, 6, 7]
[1, 8, 9, 10, 11]
Counter({8: 1, 1: 1, 10: 1, 11: 1, 9: 1})

我想要完成的是程序读取第一行,运行计数器以检查数字出现的次数,然后读取第二行,重新计数(即将计数添加到先前的计数)。 / p>

我哪里错了?它目前甚至没有计算数字,因为有超过1个“1”的实例。

2 个答案:

答案 0 :(得分:2)

您可以使用collections.Counter的{​​{3}}方法,否则每次迭代都会覆盖counts

from collections import Counter

counts = Counter()
with open("lottoresults.txt") as inf:
    for each_line in inf:
        counts.update(int(i) for i in each_line.split(','))
print(counts)

结果

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

答案 1 :(得分:0)

from collections import Counter

cnt = Counter()
with open("lottorresults.txt") as f:
    for line in f.readlines():
        numbers = [int(n) for n in line.strip().split(",")]
        cnt.update(numbers)

你想要正确的代码吗?