带计数的Python列表理解
我有一个脚本,它在减法后计算值,检查范围并将计数写入文件中的某个范围。 我知道它可以更短,我试着做列表综合,但它不起作用。请帮忙带计数的Python列表理解,python,Python,我有一个脚本,它在减法后计算值,检查范围并将计数写入文件中的某个范围。 我知道它可以更短,我试着做列表综合,但它不起作用。请帮忙 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
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 - 5
in range 1000-2000 - 5
in range 2000-5000 - 5
in range 5000-10000 - 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
从集合导入defaultdict
界限=[1010050010002000500010000]
计数=defaultdict(int)
以open(“result.txt”、“rt”)作为f_i:
对于f_i中的行:
a、 b=(int(浮点(令牌))表示第行中的令牌。拆分(“-”)
c=a-b
如果c<0:
持续
对于边界内的边界:
如果c
我是在新的py文件中实现的,因此我只在主文件中实现完全工作的代码)
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