尝试从列表中删除项目时出现“ IndexError:列表分配索引超出范围”

时间:2018-10-04 16:38:18

标签: python python-3.x list csv random

此刻,我正在尝试创建一个将应用我的代码的python应用程序,并创建一个包含歌曲的列表。然后从歌曲列表中随机选择的问题中创建一个随机问题。我知道令人困惑。

这是我的代码,希望有人能提供帮助。我似乎收到了错误:

'del question[count]
IndexError: list assignment index out of range'.

根据我的理解,我认为这并不超出范围,并且我花了数小时试图找出答案。这是我的代码:

import csv, random

#creating random questions
def random_songs(username):
    songBook = open('songs.csv', 'r')
    con_song = csv.reader(songBook)
    user = open('user_data.csv', 'a')
    con_user= csv.writer(user, delimiter = ',')
    class data():
        songs = []
        count = 0
        song_name = []
        artist_name = []
        song_answer = []
        song_question = []


    #Setting the song name and artist into a list.
    for i in con_song:
        for x in i:
            data.songs.append(x)

    #Splitting up the data from the csv file into song name and artist name.
    for length in range(0, len(data.songs)):
        if data.count % 2 == 0:
            data.song_name.append(data.songs[data.count])
            data.count += 1
        else:
            data.artist_name.append(data.songs[data.count])
            data.count += 1

    #Randomly chosing a song
    for i in range(0, 1):
        number = random.randint(0, len(data.song_name))
        data.song_answer.append(data.song_name[number])
    #Generating the question
    #print(data.song_answer)

    question = []
    for s in data.song_answer:
        question = list(s)
        print(s)
        length_s = int(len(s) -1)
        count = 1
        for i in range(length_s):
            if count <= length_s and count > 1:
                print('good')
                count = int(count)
                del question[count]
                count += 1
            else:
                print('bad')
                count += 1



random_songs('James')

这是链接上的歌曲csv文件项目: https://drive.google.com/open?id=1LxPlKF0pduXE1_r7WWzlwzMZ0mKeY4yY

我希望您能提供帮助,否则一旦解决就将对您有所帮助。

先谢谢了。     詹姆斯·麦卡农

2 个答案:

答案 0 :(得分:0)

让我们改善循环。

第一个for循环似乎合法,因此您可以保留该计数,只需删除count

for s in data.song_answer:
        questions = list(s)
        print(s)

第二个for循环可以这样替换:

for question in questions:
        print('good')
         questions.remove(question)

我们不需要在python中使用range,您可以删除迭代。我没有对此进行测试,但是如果问题是有效的清单,它应该可以工作。

答案 1 :(得分:0)

我对您要做什么没有确切的了解,但希望这会为您指明正确的方向

import csv
import random

class Song:

    def __init__(self, name, artist):
        self.name = name
        self.artist = artist
        self.question = None
        self.answer = None

    def __str__(self):
        return f'{self.name} by {self.artist}'

    def __repr__(self):
        return self.__str__()

songBook = open('songs.csv', 'r')
songs = []
for i in songBook:
    # split gives you a list with the two fields
    x = i.split(',')
    songs.append(Song(x[0],x[1]))

for song in songs:
    self.answer = random.choice(songs).name