0

这是我试图实现的代码示例:

def notes():            
    print "\nPlease enter any notes:"
    global texts
    texts = []
    if not texts:
        print "no notes exist."
        write_note()
    else:
        print "this note already exists"

def write_note():
    while True:
        global txt
        txt = raw_input(">>> ")
        if not txt:
            break
        else:
            texts.append(txt)
    print "\nNote(s) added to report."
    notes_menu()

def print_note():
    new_report.write("\nNotes:")
    for txt in texts:
        new_report.write("\n-%r" % txt)
    print "Note Printed to %r. Goodbye!" % file_name
    exit(0)

我的目标是在第二次(或无限期)调用“notes()”时将新输入添加到“文本”列表中并且不覆盖列表。我试图至少在调用“notes()”时确定列表是否为空。但是每次我这样做时,无论我在上次调用期间在“文本”中创建了多少项目,它总是打印“没有笔记存在”。

在这一点上,我有点不知所措。我查看了字典功能,但我不确定如何将其合并到此代码中。有人有什么建议/建议吗?

4

3 回答 3

0

我同意建议更好的设计是创建一个包含文本的类的评论。但是,就目前的代码而言,在我看来texts = []应该在主代码中, outside notes(),以便该行只运行一次。

于 2013-03-29T02:05:21.390 回答
0

在不改变你上面的太多内容的情况下,我可以建议一个简单地请求新注释并将注释附加到现有列表的函数:

>>> notes = []
>>> def write_note(notes):
...     while True:
...         new_note = raw_input('>>> ')
...         if not new_note:
...             break
...         else:
...             notes.append(new_note)

这是否符合您的要求?

于 2013-03-29T02:13:49.147 回答
0

当您调用 texts = [] 时,您将 text 设置为一个空列表,从而清除之前设置的任何项目。删除那条线应该会有所帮助。

另外,我想你可能想使用 .extend() 函数。Append 将一个项目添加到列表的末尾,即:

>>li = [1,2,3]
>>li2 = [4,5,6]
>>li.append(li2)
li = [1,2,3,[4,5,6]]

其中 extend() 连接两个列表:

>>li = [1,2,3]
>>li2 = [4,5,6]
>>li.extend(li2)
li = [1,2,3,4,5,6]

这可以在潜入 python时找到

于 2013-03-29T02:29:02.123 回答