2011-03-23 185 views
1

我是一名R新手,正在为我的漫画创建一个基本的“数据库”。 但是,我有一个问题。将值添加到列表

这个想法是把每个新条目作为一个列表。 我认为我可以将列表设置为如下所示。

[Thor, 50, Marvel] 
[Thor, 51, Marvel] 
[Thor, 52, Marvel] 
... 
eventually, I 'd like to include entries for story arc, writer, artist, etc. 

但是,我用下面的代码在漫画进入和已经发现,每一个新的条目被刚添加到列表的末尾。

option = 0 
comicdb = [] 

while option != 3: 
    print "--------------------------" 
    print "1. Add a New Comic Book" 
    print "2. Print the Database" 
    print "3. Quit" 
    option = int(raw_input("Pick an Option: ")) 
    if option == 1: 
     title = raw_input("Comic Book Title: ") 
     issue = int(raw_input("Issue Number: ")) 
     publisher = raw_input("Publisher: ") 
     comicdb.append(title) 
     comicdb.append(issue) 
     comicdb.append(publisher) 
     print comicdb 

运行代码几次之后,列表看起来像:

['Thor', 50, 'Marvel', 'Thor', 51, 'Marvel', 'Thor', 52, 'Marvel'] 

我假设下列情况之一是错误的,但我无法弄清楚:

  1. 追加是错误的命令使用
  2. 我应该使用字典或元组替代列表

帮助!

+0

我不完全明白你想要发生什么。问题顶部的结构应该是什么?每行都有一个列表,但列表中有什么?他们是否应该在列表中,如'[['a',1],['b',2]]'? – senderle 2011-03-23 02:59:12

+0

这实际上应该是三个独立的列表。 – ATMathew 2011-03-23 03:03:06

+0

好的,但他们在哪里存储? – senderle 2011-03-23 03:06:31

回答

2

答案很简单。您将3个单词插入列表中,而不是追加包含3个单词的列表。

它应该是这样的:

option = 0 
comicdb = [] 

while option != 3: 
    print "--------------------------" 
    print "1. Add a New Comic Book" 
    print "2. Print the Database" 
    print "3. Quit" 
    option = int(raw_input("Pick an Option: ")) 
    if option == 1: 
     title = raw_input("Comic Book Title: ") 
     issue = int(raw_input("Issue Number: ")) 
     publisher = raw_input("Publisher: ") 
     temp_list = [] 
     temp_list.append(title) 
     temp_list.append(issue) 
     temp_list.append(publisher) 
     comicdb.append(temp_list) 
     print comicdb 
3

您应该使用嵌套结构。

comicdb.append((title, issue, publisher)) 
1

您需要列表或词典列表。

record = {} 
record['title'] = raw_input("Comic Book Title: ") 
record['issue'] = int(raw_input("Issue Number: ")) 
record['publisher'] = raw_input("Publisher: ") 
comicdb.append(record) 
print comicdb 
0

虽然我很赞赏你的努力,从头开始编写一个数据库,我必须建议你看看SQLAlchemy - 一个Python“的对象关系映射”即允许您将Python对象连接到类SLQ数据库(主要是SQLite,最简单的,无服务器的数据库)。很少有代码可以达到的复杂性让我感到惊讶。它干净,功能强大,易于理解,并且迅速增长。

我在工作中非常成功地使用它,并在家中跟踪我所有的女儿图片(我有更多兆字节(teras?)的女儿在家里的照片比我在卡西尼号航天飞机上工作时要好, )。

所以,如果你只是练习 - 继续前进。如果你想站在坚实的基础上,并有一个伟大而整洁的应用程序来跟踪你的漫画,那么看看任何数据库管理器,但我推荐Python/SQLAlchemy。

干杯。

+0

感谢您的建议。我只是想从基础开始,最终以SQLAlchemy的方式工作。 – ATMathew 2011-03-23 15:26:26

+0

我仍然认为实现一个SQLAlchemy解决方案(或者,对于Python的任何数据库管理器)更容易。换句话说,你不需要“让你通过” - 他们是非常方便的。 – Escualo 2011-03-25 16:09:12