簡體   English   中英

如何在python中的for循環下使用兩個不同的循環

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

我們必須計算在保存為 csv 文件的 Excel 表中每行的第二列中出現大於 130 的數字和小於 -70 的數字的次數。 我需要一個循環,但我已經在它上面有一個循環來計算行中的不同列。 我似乎無法得到一個循環所有行 [4] 並將其計算為一個變量的代碼。 這是我的代碼。

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)

它適用於 if 循環並打印 'ave' 但似乎跳過了 while 循環。 提前致謝

條件float(row[2]) >= 130 and float(row[2]) <= -70在邏輯上是不正確的。 假設數字是 230,所以230>=130為真,但230<=-70為假,因此條件評估為假。

所以使用這個:

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