如果在使用字典或列表时语句不起作用

时间:2019-04-07 04:32:02

标签: python list csv dictionary

我有一个带有学生证的表格和学生已读过的幻灯片页面。 现在,我需要打印出那些阅读200多张幻灯片的学生,并计算出其中的几张。我尝试将csv导入列表和字典。 我发现无法像从C语言中学到的那样使用if和while循环。

#1
import csv
f = open('student_example.csv','r')


for row in csv.reader(f):
     with open('student_example.csv', mode='w') as outfile:
         writer = csv.writer(outfile)
         [k,v] = row
         f[k] = v
         k = 0
         print (f[2])
         while k < 71:    #There are 71 students
            k += 1
            if f[k] >= 200:
                print (f[k])
#2
import csv

with open('student_example.csv', mode='r') as infile:
   reader = csv.reader(infile)

   with open('student_example_new.csv', mode='w') as outfile:
       writer = csv.writer(outfile)

       mydict = {rows[0]:rows[1] for rows in reader}
       print(len(mydict))
       k = 200
       for rows[1] > k in reader:
            print(rows[1])

样本输出应为: 通过了13名学生:dict_keys(['B046060035','B064020028','B064020052','B064030002','B065040041, 'B066060019','B066090002','B073040038','B074020003','B074020024','B074020043','B074020053','B074020055'])

1 个答案:

答案 0 :(得分:0)

使用您的第一次尝试,您可以通过这种方式进行操作。 您想打开自己的文件,然后遍历学生。 如果> 200

,请检查每位学生他们读了多少张幻灯片并将其写入outfile
import csv
f = open('student_example.csv','r')

with open('student_example.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
    for row in csv.reader(f):
        [student_id, slides] = row
        if slides > 200:
            writer.writerow(student_id)
            print (student_id)