Python - 如何使用 Counter 逐行计数
Python - how to count with Counter line by line
我有以下代码可以打开包含逗号分隔数字的文本文件。
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})
我想要完成的是让程序读取第一行,运行计数器检查数字出现的次数,然后读取第二行,重新计数(即添加计数到以前的计数)。
我哪里错了?目前甚至没有计算数字,因为“1”的实例不止 1 个。
可以使用collections.Counter
的update
方法,否则每次迭代都会覆盖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})
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)
是你想要的正确代码吗?
我有以下代码可以打开包含逗号分隔数字的文本文件。
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})
我想要完成的是让程序读取第一行,运行计数器检查数字出现的次数,然后读取第二行,重新计数(即添加计数到以前的计数)。
我哪里错了?目前甚至没有计算数字,因为“1”的实例不止 1 个。
可以使用collections.Counter
的update
方法,否则每次迭代都会覆盖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})
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)
是你想要的正确代码吗?