2017-10-15 17 views
-4

我是一名初學者程序員,正在爲我的計算機科學GCSE練習此代碼。 我使用此代碼,如何更正和索引if語句中的錯誤?

import random 
file = open("OCR tunes1.csv","r") 
temp = file.read() 
file.close() 

tempList = temp.split("\n") 
print(tempList[1]) 

OCRtunes = [] 
for item in tempList: 
    record = item.split(",") 
    OCRtunes.append(record) 
print(OCRtunes) 
genreOptions = ["pop", "rock", "classical"] 
limit = random.choice(genreOptions) 
limit = '"' + limit + '"' 
print(limit) 

increasing = 0 
options = [] 
while True: 
    if OCRtunes[increasing][2] == limit: 
     options.append(OCRtunes[increasing][0]) 
     increasing += 1 
    else: 
     increasing += 1 
    if increasing == 20: 
     False 
print(options)  

我得到這個錯誤。

Traceback(most recent call last) : 
    File "C:/Users/Jude/Documents/school/computer science/NEA/random playlist genre.py, line 23, in <module> 
    if len(OCRtunes[increasing][[2]) == limit: 
IndexError: list index out of range 
>>> 

如何清除錯誤?

+2

請發表您的代碼和追蹤文本 - 不是圖片... –

+0

你應該張貼您的代碼。 –

+1

[不要發佈代碼圖片(或鏈接到他們)](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so - 當問一個問題) – jezrael

回答

-1

要處理列表中的每個元素,使用for -loop:

import random 
import csv 

genre_options = ["pop", "rock", "classical"] 

with open("OCRtunes1.csv") as tunes: 
    ocr_tunes = list(csv.reader(tunes)) 

limit = random.choice(genre_options) 
options = [] 
for tune in ocr_tunes: 
    if tune[2] == limit: 
     options.append(tune[0])