使用while循环向列表添加元素而不覆盖之前的元素

-1 投票
1 回答
1008 浏览
提问于 2025-04-16 15:11

我正在处理事件和数据库的相关内容。

我创建了一个循环,这个循环会不断地把我的事件(对象)添加到数据库里。同时,只要用户不输入“exit”这个命令,主程序里的一个命令就会一直运行下去。

我遇到的问题是,每次命令要求添加一个事件时,之前的事件在每次循环中都会被覆盖掉。

在这里,“事件”这个词就像“exit”命令一样。所以每当输入这个词和一个事件字符串时(我已经实现了一个功能,可以把事件字符串转换成事件对象),它就会不断地把事件对象添加到数据库中。

def parse(command):
    '''Parse a command string.'''
# gist of event class Event(description, time, date, duration) not part of this function event string could be: '"Movie night" today 10:00pm'

    store_event = Database() # where I should save my event objects
    cmd_str = command.split() 
    a_lst =[]

    while cmd_str[0] == "event": #while event is a command that the user wants
        cmd_str = command.split()
        cmd_str.pop(0) # I don't need the word "event" just the event string after it.
        new_str = ' '.join(cmd_str)
        an_event = parseevent(new_str) # converts string object to event objects
        a_lst.append(an_event)

谢谢!

1 个回答

1

我觉得你想要这样做:

def parse(command, a_lst):
    '''Parse a command string.'''
    a,b = command.split(None,1)
    if a == "event":
        a_lst.append(b)


store_event = Database() # where I should save my event objects
parse('event blahblahbla',store_event)
parse('event youtchouiya',store_event)
parse('event print ramantiyi',store_event)
parse('event import re',store_event)
# etc etc 

撰写回答