简体   繁体   English

如何在python中的for循环下使用两个不同的循环

[英]How use two different loops under a for loop in python

We have to compute how many times a number greater than 130 and a number less than -70 occurred in the 2nd column of each row in an excel sheet, saved as a csv file.我们必须计算在保存为 csv 文件的 Excel 表中每行的第二列中出现大于 130 的数字和小于 -70 的数字的次数。 I need a loop but i already had a loop above it for computing a different column in the rows.我需要一个循环,但我已经在它上面有一个循环来计算行中的不同列。 I can't seem to get a code that loops around all the row[4] and compute it into one variable.我似乎无法得到一个循环所有行 [4] 并将其计算为一个变量的代码。 Here is my code.这是我的代码。

import csv
import os
total = 0
count = 0
ring = 0
column = []
with open("2.5_week.csv") as source:
    rdr = csv.reader(source, delimiter=',')
    next(rdr, None) # to skip the header

    for row in rdr:
        if float(row[4]):
            total = total + float(row[4])
            count = count + 1  
        while (float(row[2]) >= 130 and float(row[2]) <= -70):
            ring = ring + 1
            print(ring)
        percent = (ring/count) * 100
        ave = total / count
    print (ave, percent)

It works for the if loop and prints the 'ave' but seems to skip the while loop.它适用于 if 循环并打印 'ave' 但似乎跳过了 while 循环。 Thanks in advance提前致谢

The condition float(row[2]) >= 130 and float(row[2]) <= -70 is logically incorrect.条件float(row[2]) >= 130 and float(row[2]) <= -70在逻辑上是不正确的。 Lets say the number is 230, so 230>=130 is true but 230<=-70 is false and hence the condition evaluates to false.假设数字是 230,所以230>=130为真,但230<=-70为假,因此条件评估为假。

So use this:所以使用这个:

while (float(row[2]) >= 130 or float(row[2]) <= -70) #or instead of and

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM