繁体   English   中英

使用多个while循环?

[英]Using multiple while loops?

我有一个运行良好的代码。 我能够使它在2008行中打印一行。 但是,当我决定循环以将其递增到2014年时,它陷入了困境。 有一个更好的方法吗? 我真的以为我在那里呆了一分钟。 csv文件的中心列有多个“标题”,左列是从2008年到2014年的年份。值在右列,并且每一行都有所不同。

这是我的代码:

import csv
from math import floor
import sys

ohu = 'Occupied Housing Units'
vhu = 'Vacant Housing Units'
thu = 'Total Housing Units'
yr = 2008
limit = 2014
filename = 'denton_housing.csv'


with open(filename, 'r', encoding='utf8', newline='') as f:
    housing_stats = []
    for row in csv.DictReader(f, delimiter=','):
        year = int(row['year'])
        field_name = row['title_field']
        value = int(row['value'])
        denton_dict = {'year': year, 'title_field': field_name, 'value': value}
        housing_stats.append(denton_dict)

        while int(row['year']) >= yr and int(row['year']) <= limit and row['title_field'] == vhu:
            vac_unit = int(row['value'])
        while int(row['year']) >= yr and int(row['year']) <= limit and row['title_field'] == thu:
            tot_unit = int(row['value'])
        while int(row['year']) >= yr and int(row['year']) <= limit and row['title_field'] == ohu:
            occ_unit = int(row['value'])
            print(yr, "             ", "{0:.0f}%".format(100 * (vac_unit / tot_unit)),\
        "                      ", "{0:.0f}%".format((occ_unit / tot_unit) * 100))
            yr+1

您有3个while循环,只有最后一个包含您的增量器,您的增量器应为yr += 1 (是yr = yr = 1缩写),而不仅仅是yr+1

您还需要更改您的方法,因为您想在这些年和行中进行迭代。

我建议保留有关年度的字典,以及每年的vhu,ohu和thu数据。 最终结果可能类似于“ {'2008':{'vhu':1,'ohu':5,'thu':6},'2009':...}。

暂无
暂无

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

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