【问题标题】:I can not get the code snippet below to output the proper results我无法获得下面的代码片段来输出正确的结果
【发布时间】:2021-07-16 05:59:00
【问题描述】:

CSV 文件有大约 6 个单词 business 条目以及其他几个应该与以下条目匹配的条目。但是,该循环仅正确显示“业务”的计数

with open('majors.csv') as csvfile:
    for majorName in majorsList:
        ctr = 0
        print(majorName)
        #for line in csvfile:
            #if str(line.strip()) == str(majorName):
                #ctr += 1
                #print("WORKED")
        #print("Number of students thinking about " + majorName + ": " + str(ctr))```


Example output:
Business
WORKED
WORKED
WORKED
WORKED
WORKED
WORKED
Number of students thinking about Business: 6
Health
Number of students thinking about Health: 0
History/Social Science
Number of students thinking about History/Social Science: 0
Engineering
Number of students thinking about Engineering: 0
Communications
Number of students thinking about Communications: 0
Performance Arts
Number of students thinking about Performance Arts: 0
Education
Number of students thinking about Education: 0
Computers
Number of students thinking about Computers: 0
Other
Number of students thinking about Other: 0

【问题讨论】:

    标签: python csv for-loop


    【解决方案1】:

    您需要为majorsList 中的每个项目打开majors.csv
    因此,您的代码将如下所示。

    for majorName in majorsList:
        with open("majors.csv") as csvfile:
            ctr = 0
            print(majorName)
            for line in csvfile:
                if str(line.strip()) == str(majorName):
                    ctr += 1
                    print("WORKED")
            print("Number of students thinking about " + majorName + ": " + str(ctr))
    

    【讨论】:

    • 如果它对你有用,那么请点击上面的勾号接受答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多