到目前为止,经过几个小时后,我仍然无法弄清楚这一点。任何帮助或任何人可以提供的任何东西将非常感激。非常感谢提前。
stats.append({
'rounds' : round_playing,
'round' : [{'name' : str(list_players[i]['name']),
'score' : list_players[i]['score']
}]
})
list_players:
list_players.append({'name': '',
'score': 0})
打印出来
for s in stats:
print("*************************************")
print("Round: " + str(s['rounds']))
print("*************************************")
for p in s['round']:
print("@" + str(p['name'])
+ "\nScore: " + str(p['score'])+ "\n")
print("*********************")
目前:
============================
Round 1
============================
Player1
Score: 11
============================
Round 1
============================
Player2
Score: 23
期望的结果:
============================
Round 1
============================
Player1
Score: 11
Player2
Score: 23
============================
Round 2
============================
Player1
Score: 55
Player2
Score: 7
有人建议这样的事情:
def buildList(p):
for i in range(len(p)):
list_players.append({'name': '', 'score': 0})
不确定。
答案 0 :(得分:3)
TL; DR - 不要将单个玩家条目附加到stats
。相反,为每一轮追加完整的数据(所有参与者)。
您的代码中的问题是正在使用的数据结构,这使得难以以正确的方式打印数据。正如评论中所提到的,rounds
的每个元素中stats
值的长度始终为1
,因此您将获得此类输出。
虽然可以为stats
使用这样的数据结构,但考虑到您希望打印数据的格式,它可能不是最佳选择。它更好收集与单轮相对应的所有数据。因此,我的答案中的想法是将与单个回合相对应的所有数据收集到stats
的单个元素中。
假设 - 我假设list_players
在您构建stats
时使用新数据动态更新。
构建 list_players
- 保持原样,因为您打算在整个列表中运行。
构建 stats
- 如果您的整数始终从1
开始并按顺序增长,您只需创建一个列表,其中索引i
代表圆形i+1
。如果你有更复杂的圆名,你可以使用字典,键是圆号,因为这样可以轻松访问特定轮数的统计数据。
此外,您可以直接复制list_players
而不是在其上运行循环,因为您正在构建相同的数据结构。
有了一个清单,
for round in range(0, total_rounds):
# Modify scores in `list_players` correctly
# You have to copy the whole list, since `list_players` will
# change over the course loop
stats.append(list_players[:])
用字典
stats = {}
for round in round_numbers:
# Modify scores of `list_players` correctly
# Again, make sure you copy the list as it's dynamic
stats[round] = list_players[:]
打印结果 -
如果将stats
保留为列表,我已使用enumerate()
功能。
for index, round in enumerate(stats):
# Always use 4 space indentation
print("*************************************")
print("Round: " + str(index+1)
print("*************************************")
for p in round:
print("@" + str(p['name']) +
"\nScore: " + str(p['score'])+ "\n")
print("*********************")
用字典
for key, value in stats.iteritems():
# Always use 4 space indentation
print("*************************************")
print("Round: " + str(key)
print("*************************************")
for p in value:
print("@" + str(p['name']) +
"\nScore: " + str(p['score'])+ "\n")
print("*********************")