我想保存一个不断改变存储在其中的值的变量。我想保存每个值。我该怎么做?

I want to save a variable that is constantly going to be changing the value thats stored in it. I want to save each value. How would I do that?

我有一个不断存储用户发送的消息的 discord 机器人。我想将这些消息保存在某个地方,然后在调用机器人时,我想随机发送我保存的其中一条消息。或者向他们展示我已保存的所有消息的列表。

代码如下:

@client.command()
async def quote(ctx,user:discord.Member,*,message):
    color=discord.Color(value=0x9C2A00)
    async for messages in ctx.channel.history(limit=1):
        pass
    em=discord.Embed(color=color,title=message,description=f'-{user}, [original](https://discordapp.com/channels/{messages.guild.id}/{messages.channel.id}/{messages.id})')
    await ctx.send(embed=em)

我想继续保存 'em' 变量。或者我更具体地猜测 em 变量的标题和描述。

我尝试将变量 em 存储在列表中并且成功了!但是,它只存储了 em 的最后一个值。我想存储 em 的每个值。 我所做的如下:

em=#the code
em_list=[]
em_list.append(em)

但是,每次给 'em' 一个新值时,列表中的旧值都会被新值覆盖。我想存储每个值,而不仅仅是最新的一个。

有两种方便的方式来存储数据:列表或字典。

如果您存储的是一对 key:value 数据,最好使用字典。在字典中,键是指向值的内容。每个值都有一个键,通过它可以在字典中找到它。因此,如果您想将数据存储为 key-value 对,其中键可以是 'user' 名称或 'message' 名称,而值可以是 'em'变量。

em_dict = {}
em_dict[message] = em
# 'em' can then be used to store another item, and that item can be stored in
# the em_dict with a different message or user key

而如果您只想存储 'em' 的内容,而不管它对应的是 'user' 或 'message' 标题,您只需创建一个包含所有内容的列表'em' 临时存储的变量:

em_list = []
em_list.append(em)
# Then change the value of em and store it using the list's append() method.

字典和列表都可用于使用 for 循环存储 'em' 值

同样,请参阅任何有关列表处理的教程。特别是

# Do this once: initialize your list
em_list=[]
...

# In your code that executes multiple time:

    em=#the code
    em_list.append(copy(em))

# hHen that is all done ...
for em in em_list:
    # Do whatever you want with each element in the list
    print(em)

您需要复制变量。否则每次更新时,它的所有引用都将指向新值。

em_list = []
# when em updates:
em2 = em
em_list.append(em2)
# when em updates again:
em3 = em
em_list.append(em3)

更好的方法是根本不将值存储在变量中。您可以直接将它们附加到列表中,无需名称:

em_list = []
em_list.append(1)
em_list.append(2)
em_list.append(3)