使用两个计数器变量来跟踪总计数和阳性数。在开始时将它们设置为0,然后无论何时您想要添加1,在循环中使用+= 1。
然后,通过去掉百分比符号,然后使用以下方法将字符串转换为数字,测试百分比是否大于0。if float(row[0].strip('%')) > 0。你可以将此更改为>=如果您想将0包含在“正”类别中。totalCount = 0
numberOfPositives = 0
with open('FL%.csv', 'r') as file2:
reader = csv.reader(file2)
reader.next() # this skips the first row of the file
# this iteration will start from the second row of file2.csv
conditionMet = False
for row in reader:
if conditionMet == True:
if float(row[0].strip('%')) > 0: # change > to >= if you want to count 0 as positive
print "FA, 1",row[0],',', ','.join(row[1:5]) # print 1 if positive
numberOfPositives += 1 # add 1 to numberOfPositives only if positive
else:
print "FA, 0",row[0],',', ','.join(row[1:5]) # print 0 if not positive
totalCount += 1 # add 1 to totalCount regardless of sign
conditionMet = False # or break if you know you only need at most one line
if row[1:5] == val1:
conditionMet = True
然后,你可以计算你所需的总和百分比。totalCount和numberOfPositives:print 'Total Count =', totalCount
print 'Percentage of Positive numbers =', numberOfPositives * 100./totalCount, '%'
2627

被折叠的 条评论
为什么被折叠?



