【发布时间】:2018-11-27 06:48:30
【问题描述】:
编写一个名为“internet_histogram”的函数,它不带参数也不返回值。在测试环境中将有一个名为“survey.csv”的文件,其中包含如上所述的调查结果(该文件有一个标题行,您的代码可以解决很多问题)。编写一个名为“histogram.csv”的新文件,其中包含代表“internet_use,frequency”的 2 列,并且没有标题行,其中将包含 28 到 29 岁的响应者结果的直方图,包括端点年龄。您的文件将恰好有 6 行 internet_use 值为 1-5 对应于 intfreq 结果和 6 用于回答 2 到 eminuse 的响应者。阅读调查结果文件并跟踪该年龄范围内有多少响应者回答了这 6 个选项中的每一个,并将这些计数按照 internet_use 从 1 开始的顺序写入您的“histogram.csv”文件。 示例 histogram.csv: 1,5 2,7 3,0 4,1 5,2 6,4
我的代码:
import csv
def internet_histogram():
count_6 = 0
count_5 = 0
count_4 = 0
count_3 = 0
count_2 = 0
count_1 = 0
with open("survey.csv",'r') as f:
reader = csv.reader(f)
with open("histogram.csv", 'w') as g:
writer = csv.writer(g)
next(reader)
for line in reader:
if int(line[3]) >= 28 and int(line[3]) <= 29:
if line[2] != '':
if int(line[2]) == 1:
count_1 += 1
if int(line[2]) == 2:
count_2 += 1
if int(line[2]) == 3:
count_3 += 1
if int(line[2]) == 4:
count_4 += 1
if int(line[2]) == 5:
count_5 += 1
else:
count_6 = count_6 + 1
arr = [[1, count_1], [2, count_2], [3, count_3], [4, count_4], [5, count_5], [6, count_6]]
for i in arr:
writer.writerow(i)
输出: 写道:“1,26 2,29 3,2 4,3 5,1 6,1 " 预期:“1,26 2,29 3,2 4,3 5,1 6,2 "
我认为这是 else 语句的问题,但我不太确定,任何帮助将不胜感激。
【问题讨论】:
-
看起来您的
else缺少缩进。所以它指的是for而不是if。 -
我早些时候尝试过,它只是变成了一个循环,有超过 1000 个值循环播放
-
很难判断我没有看到的东西,但是当您尝试这样做时,您是否取消了第二个
for循环的缩进? -
另外,您的
else只会引用最后一个if。也许使用elifs。 -
是的,我为 else 语句尝试了多种不同的缩进方法
标签: python file-writing