简体   繁体   中英

Finding a frequency of numbers in a list

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)

This code loops through a text file with various negative and positive numbers and adds them together starting from zero. However I was wondering how to find how many times each number occurs in this file?

Collection's Counter is expecting an iterable as an argument and not an item:

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)

But if efficiency is not an issue for you and you're just trying to sum all numbers in a file and count their frequency, you don't need to import a library just to do that:

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)}

Your file has an integer on each line, and you want the total sum and the frequency of each integer, right? Try this.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM