Lotarc
Lotarc

Reputation: 99

Python list comprehension with count

I have a script which is counting values after substraction, do check to ranges and write count in file to a certain range. I know that it can be shorter, and i tried to do list comprehensive and it doesn't work. Help with it please

count_0_10 = 0
count_10_100 = 0
count_100_500 = 0
count_500_1000 = 0
count_1000_2000 = 0
count_2000_5000 = 0
count_5000_10000 = 0

with open("result.txt", "rt") as f_i:
    for line in f_i:
        orsDist, localDist = line.split("-")
        a = int(float(orsDist))
        b = int(float(localDist))
        c = a-b
        if 0 <= c < 10:
           count_0_10 += 1
        elif 10 <= c < 100:
           count_10_100 += 1
        elif 100 <= c < 500:
           count_100_500 += 1
        elif 500 <= c < 1000:
            count_500_1000 += 1
        elif 1000 <= c < 2000:
            count_1000_2000 += 1
        elif 2000 <= c < 5000:
            count_2000_5000 += 1
        elif 5000 <= c < 10000:
            count_5000_10000 += 1

with open("result.txt", "w") as f_o:
    f_o.write(f'in range 0-10 - {count_0_10}\n')
    f_o.write(f'in range 10-100 - {count_10_100}\n')
    f_o.write(f'in range 100-500 - {count_100_500}\n')
    f_o.write(f'in range 500-1000 - {count_500_1000}\n')
    f_o.write(f'in range 1000-2000 - {count_1000_2000}\n')
    f_o.write(f'in range 2000-5000 - {count_2000_5000}\n')
    f_o.write(f'in range 5000-10000 - {count_5000_10000}\n')

The output is should be this:

in range 0-10 - 0
in range 10-100 - 0
in range 100-500 - 1
in range 500-1000 - 4
in range 1000-2000 - 0
in range 2000-5000 - 0
in range 5000-10000 - 0

But i'm getting this

in range 0-10 - 0
in range 10-100 - 0
in range 100-500 - 1
in range 500-1000 - 5
in range 1000-2000 - 5
in range 2000-5000 - 5
in range 5000-10000 - 5

Upvotes: 0

Views: 82

Answers (1)

user2390182
user2390182

Reputation: 73450

The following will go some way in DRYing up your code:

from collections import defaultdict

bounds = [10, 100, 500, 1000, 2000, 5000, 10000]
counts = defaultdict(int)

with open("result.txt", "rt") as f_i:
    for line in f_i:
        a, b = (int(float(token)) for token in line.split("-"))
        c = a-b
        if c < 0: 
            continue
        for bound in bounds:
            if c < bound:
                counts[bound] += 1
                break

with open("result.txt", "w") as f_o:
    lower = 0
    for bound in bounds:
        # f_o.write(f'in range {lower}-{bound} - {counts[bound]}\n')
        f_o.write('in range {}-{} - {}\n'.format(lower, bound, counts[bound]))
        lower = bound

Upvotes: 1

Related Questions