当第二次调用一个方法时,如何在不重写的情况下添加到列表中?

2024-05-08 18:03:34 发布

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

下面是im试图实现的代码示例:

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()”时,将新输入添加到“text”列表中,并且不覆盖列表。我试图至少在调用“notes()”时确定列表是否为空。但每次我这样做,不管我在前一次通话中在“文本”中创建了多少个条目,它总是打印“不存在注释”

我现在有点不知所措。但我不确定如何将它合并到这个函数中。有人有什么建议吗?在


Tags: toreporttxt列表newifdefnot
3条回答

当您调用texts=[]时,您将文本设置为空列表,将先前设置的所有项都清空。去掉那条线应该会有帮助。

另外,我想您是否可以使用.extend()函数。追加在列表末尾添加一个项目,即:

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

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

^{pr2}$

这可以在dive into python上找到

我同意那些建议更好的设计应该是创建一个包含文本的类的评论。但是,对于现有的代码,我认为texts = []应该在主代码中,在notes()之外,这样该行只运行一次。

如果不改变现有的请求列表,我可以简单地建议您改变现有的功能:

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

这是你想要的吗?

相关问题 更多 >