将值附加到 Python 中的键?

Appending a value to a key in Python?

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]

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

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

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

来自shelve.open的相关文档:

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

请注意,您可以跳过使用 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)