【问题标题】:Appending a value to a key in Python?将值附加到 Python 中的键?
【发布时间】:2015-04-15 18:23:20
【问题描述】:
if savescores == "y":
        name = raw_input("Enter your name.")
        datfile = filename[0:-4] + ".dat"
        highscores = shelve.open(datfile)
        try:
            highscores[name].append(score)
        except:
            highscores[name] = [score]

如果这个特定玩家已经有分数,我想将新分数附加到他已有的分数上,但显然这不起作用,因为它根本不会改变他的分数。

【问题讨论】:

  • 你能更详细地解释什么不起作用吗?乍一看,您所拥有的看起来不错(尽管我会使用 except KeyError 而不是裸露的 except)。
  • 这是“try: highscores[name].append(score)”。当我要求它打印特定球员的分数时,什么都没有改变,它只是我之前得到的分数,它应该有旧分数和新分数的列表。
  • @Shashank:你的意思是setdefault,而不是getget 不会改变字典,setdefault 会。查看d = {};d.get('x', []).append(1);print(d)的结果。
  • @StevenRumbalski 是的,我的错。 highscores.setdefault('name', []).append(score)

标签: python append shelve pickle


【解决方案1】:

Shelf 对象不会检测到您工具架中可变对象的更改。它只检测分配。

要解决此问题,请使用writeback=True 打开您的书架,并确保在完成后使用close。 (您也可以不时sync 以降低缓存的内存使用率。)

来自shelve.open的相关文档:

由于 Python 语义,架子无法知道何时可变 持久字典条目被修改。 默认修改对象 仅在分配到书架时写入(参见示例)。如果 可选writeback参数设置为True,所有访问的条目都是 也缓存在内存中,并写回sync()close();这 可以更方便地改变持久化中的可变条目 字典,但是,如果访问许多条目,它会消耗大量 缓存的内存量,它可以进行关闭操作 非常慢,因为所有访问的条目都被写回(没有办法 确定哪些访问的条目是可变的,也不是哪些是可变的 实际上变异了)。

请注意,您可以跳过使用writeback=True 打开以节省内存,但您的代码将更加冗长,如shelve 文档中的example 所示。

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2]    # this works as expected, but...
d['xx'].append(3)      # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()       # close it

顺便说一下,这段代码

try:
    highscores[name].append(score)
except:
    highscores[name] = [score]

更简洁地表示为

highscores.setdefault(name, []).append(score)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多