我是初学程序员,正在研究这段代码,为我的计算机科学GCSE练习。 我正在使用此代码,
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
>>>
如何删除错误?
答案 0 :(得分:-1)
要处理列表的每个元素,请使用for
- 循环:
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])