【发布时间】:2014-10-30 15:56:55
【问题描述】:
我有一个 Python 函数,它将玩家的姓名和分数作为参数,并确定这是否是玩家的最高分数。它通过将参数与搁置对象进行比较来实现。
搁架应该只存储每个玩家的高分;例如,不应该为名为“Joe”的人评分。
不幸的是,我不知道如何从字典列表(架子)中分离出一个字典,以便与传入的玩家字典进行比较。
这是我的代码:
import shelve
import os
def highscore(player_name, player_score):
"""
Function to return the high score from our
persistent storage of score records for a given
person.
"""
# Get our working directory
working_dir = os.getcwd()
# Create our shelf object for a player
highscore_fn = os.path.join(working_dir, 'highscore.shelve')
# Set our player info
player = {'name': player_name, 'score': player_score}
with shelve.open(highscore_fn, writeback=True) as shelf:
# Check if any records exist in the shelf
if len(shelf) == 0:
# Assign the shelf to an empty list
shelf['player_data'] = []
# Append player data to shelf
shelf['player_data'].append(player)
# Current high score for player
high_score = player.get('score')
else:
# Loop through our player data list
for data in shelf['player_data']:
# Check to see if we have data for a player
if player['name'] in data['name']:
existing_record = data
# Compare the player's new score against previous score
if player.get('score') > existing_record.get('score'):
high_score = player.get('score')
# Update our record for the player
existing_record.update(player)
else:
high_score = existing_record.get('score')
else:
high_score = player.get('score')
shelf['player_data'].append(player)
# Return the high score
return high_score
任何提示将不胜感激!
【问题讨论】:
-
你能举一个
isolate a dict from the list of dicts (shelf) for comparison against the incoming player dict的例子吗? -
你有什么理由使用字典列表而不是字典的字典吗?
-
另外(完全不相关,但)您应该永远依赖
os.getcwd()为您的应用程序数据计算路径 - “当前工作目录”并不意味着“目录你的代码文件在”,但“用户启动程序时所在的目录”(假设代码的某些部分没有将其更改为其他任何内容......)。 -
您的搁置中是否包含除
player_datadicts 列表之外的其他对象?
标签: python list dictionary shelve