优化我的Benfold法律计划

时间:2014-02-20 19:28:12

标签: python

lines=[]
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
allcount = 0

with open('city_all.txt', 'r') as file:
    for line in file:
        lines.append(line.strip())

for x in range(0,len(lines)):
    if lines[x].isdigit():
        allcount+=1
        string = lines[x]
        if string[0]=="1":
            count1+=1
        elif string[0]=="2":
            count2+=1
        elif string[0]=="3":
            count3+=1
        elif string[0]=="4":
            count4+=1
        elif string[0]=="5":
            count5+=1
        elif string[0]=="6":
            count6+=1
        elif string[0]=="7":
            count7+=1
        elif string[0]=="8":
            count8+=1
        elif string[0]=="9":
            count9+=1

print(count1/allcount)
print('{:.1%}'.format(count1/allcount))

想知道是否有必要声明我的所有变量,并压缩所有if语句?试图制作一个程序来帮助计算Benfold定律,所以我将一个txt文件放入一个列表中,然后通过每个元素并检查起始数字是什么。

1 个答案:

答案 0 :(得分:2)

您可以稍微简化一下:

counts = [0 for _ in range (10) ]

with open('city_all.txt', 'r') as f:
    for line in (x.strip () for x in f):
        if line.isdigit():
            allcount += 1
            try: counts[int(line)] += 1
            except IndexError: pass