无法获得写入所需输出的功能

问题描述 投票:0回答:1

问:“编写一个名为”internet_histogram“的函数,它不带参数,也不返回值。测试环境中会有一个名为”survey.csv“的文件,其中包含如上所述的调查结果(该文件有一个标题行,你的代码可以解决这个问题。写一个名为“histogram.csv”的新文件,其中包含2个代表“internet_use,frequency”的列,没有标题行,其中包含30到33岁的响应者结果的直方图,包括终点年龄。您的文件将正好有6行,其中internet_use值为1-5对应于intfreq结果,6对于回答2对应eminuse的响应者。阅读调查结果文件并跟踪这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/

python csv file-writing
1个回答
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计算错误。

© www.soinside.com 2019 - 2024. All rights reserved.