Q:“写一个不带参数且不返回值的名为“ internet_histogram”的函数。在测试环境中将有一个名为“ survey.csv”的文件,其中包含如上所述的调查结果(该文件具有一个标头行),编写一个名为“ histogram.csv”的新文件,其中包含2列代表“ internet_use,frequency”的列,并且没有标头行包含30至33岁年龄段的响应者结果的直方图,包括端点年龄。您的文件将有6行,internet_use值为1-5,与整数结果相对应;对于回答2为负的响应者,有6行。阅读调查结果文件,并跟踪在该年龄范围内每个响应有多少响应者这6个选项,并将这些计数按照1开头的internet_use顺序写入“ histogram.csv”文件。
示例histogram.csv
:
1,5
2,7
3,0
4,1
5,2
6,4
这是我的代码:
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]) >= 29 and int(line[3]) <= 53:
if line[2] != '':
if int(line[2]) == 1:
count_1 += 1
elif int(line[2]) == 2:
count_2 += 1
elif int(line[2]) == 3:
count_3 += 1
elif int(line[2]) == 4:
count_4 += 1
elif int(line[2]) == 5:
count_5 += 1
else:
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)
运行代码后,这是我的结果与预期结果:
**wrote**:
1,236
2,329
3,42
4,34
5,17
6,0
**expected**:
1,48
2,48
3,7
4,6
5,1
6,3
是什么导致此功能无法实现预期效果?我可以进行哪些更改?预先感谢您的帮助:)
(“ survey.csv”文件可在此数据集中提供,以供参考:http://www.pewinternet.org/dataset/jan-3-10-2018-core-trends-survey/)
答案 0 :(得分:0)
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]) >= 31 and int(line[3]) <= 47:
if int(line[0]) == 2:
count_6 +=1
if line[2] != '':
if int(line[2]) == 1:
count_1 += 1
elif int(line[2]) == 2:
count_2 += 1
elif int(line[2]) == 3:
count_3 += 1
elif int(line[2]) == 4:
count_4 += 1
elif int(line[2]) == 5:
count_5 += 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)
您的代码应如下所示,您的年龄范围有误,count_6的计算不正确。