2017-10-15 96 views
0
import csv 

f =open('Scores.csv') 
csv_f = csv.reader(f) 
    #next(readCSV) 

users = [] 
quizzes = [] 
grades = [] 

for row in csv_f: 

    user = row[0] 
    quiz = row[2] 
    grade = row[5] 

    users.append(user) 
    quizzes.append(quiz) 
    grades.append(grade) 

whatUser = input ("User: ") 

if whatUser in users: 
    coldex = users.index(whatUser) 
    theQuiz = quizzes[coldex] 
    theGrade = grades[coldex] 

    print("Username: ", whatUser) 
    print("Quizzes: ", theQuiz) 
    print("Grades: ", theGrade) 

我試圖讓該程序查找行[0]中的所有用戶,然後在行[2]和[5]上打印相關信息。正如你在附圖中看到的那樣,它只能找到1個Bob,而不是代碼運行時的第二個。Python CSV如何遍歷列表

Used file

+3

時要顯示的文字,不要附加圖像。這對我們來說是不必要的閱讀。但是,嘿,嗨!所以,你忘了問一個問題,而且你也沒有顯示你迄今爲止嘗試過的解決方案。 –

回答

1

更改最後部分:

for i in range(len(users)): 
    if users[i] == whatUser: 
     theQuiz = quizzes[i] 
     theGrade = grades[i] 

     print("Username: ", whatUser) 
     print("Quizzes: ", theQuiz) 
     print("Grades: ", theGrade) 

index(x)只會返回元素x的第一指標。因此,你必須循環和處理所有匹配。

1

你也可以遍歷用戶和打印每一個匹配: