Python列表IndexError,将列表传输到对象

时间:2011-03-03 23:25:54

标签: python list

所以我正在完成任务,而且我遇到了一个似乎无法克服的障碍。我本质上是在设计一个基本的图书馆系统。我必须从文件中读取书籍,图书管理员和顾客,然后将它们解析为列表,然后解析为对象。我已经解析了部分列表并让它们准备好用于创建对象。当我尝试从我得到的列表和 IndexError 中读取时,我遇到了问题,我无法弄清楚如何修复它。

我的列表第一项是 ISBN ,然后是标题,然后是作者,然后重复,即 [ '123','The Scarlet Letter','Nathaniel Hawthorne']

self._bookList = ['123', 'The Scarlet Letter', 'Nathaniel Hawthorne', '456', 'Lord of the Rings', 'JRR Tolkien', '789', 'A Tale of Two Cities', 'Charles Dickens', '10112', 'Wuthering Heghts', 'Emily Bronte', '131415', 'Jane Eyre', 'Charlotte Bronte', '161718', 'Pride and Predudice', 'Jane Austin']

我遇到问题的片段。我尝试过使用len(self._bookList)-1,+ 1,+ 2,+ 3。似乎没什么用。

def _addToCollection(self):
    i = 0
    while i < len(self._bookList):
        ISBN = []
        ISBN.append(self._bookList[i])
        title = []
        title.append(self._bookList[i+1])
        author = []
        author.append(self._bookList[i+2])      
        #print(self._bookList[i],self._bookList[i+1],self._bookList[i+2])
        BookCollection.addBook(self,str(ISBN[i]),str(title[i]),str(author[i]))
        i += 1

2 个答案:

答案 0 :(得分:2)

问题是您在每次迭代期间分配空列表。当您致电ISBN[i]时,列表始终只有一个元素。因此,只要i大于零,它就会失败。

解决这个问题的一种方法是注意到根本不需要列表:

def _addToCollection(self):
    i = 0
    while i < len(self._bookList):
        ISBN = self._bookList[i]
        title = self._bookList[i+1]
        author = self._bookList[i+2]
        BookCollection.addBook(self,str(ISBN),str(title),str(author))
        i += 3

我建议您先查看recipe中的石斑鱼itertools documentation,因为这似乎完全符合您的要求:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

你可以像这样使用它:

for ISBN, title, author in grouper(3, self._bookList):
    BookCollection.addBook(self, str(ISBN), str(title), str(author))

答案 1 :(得分:0)

更改 init 方法,然后执行此操作

a = BookCollection.addBook(*self._bookList)