如何更正和索引if语句中的错误?

2024-03-29 10:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初学者程序员,我正在为我的计算机科学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)    

我得到了这个错误。在

^{pr2}$

如何消除错误?在


Tags: 代码randomrecorditemtempfileoptionssplit
1条回答
网友
1楼 · 发布于 2024-03-29 10:40:33

要处理列表的每个元素,请使用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])

相关问题 更多 >