Py学习  »  Python

python列表理解与计数

Lotarc • 5 年前 • 1223 次点击  

我有一个脚本,它在减法后计算值,检查范围并将文件中的计数写入某个范围。 我知道它可以短一些,我试着做了一个全面的清单,但它不起作用。请帮忙

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

输出应该是:

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

但我明白了

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43169
 
1223 次点击  
文章 [ 1 ]  |  最新文章 5 年前
schwobaseggl
Reply   •   1 楼
schwobaseggl    5 年前

以下内容将在某种程度上干掉您的代码:

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