You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在终端以表格格式展示Python字典数据

终端类表格样式展示分数数据问题

需求:在终端中以类表格样式展示分数数据,无需复杂样式,只要呈现表格形态,同时添加每行的总分。

原代码

score = {'rounds_0': {'jack': 9, 'joe': 8}, 'rounds_1': {'jack': 11, 'joe': 13}}

players_name = ["jack","joe"]
for each_rounds in range(0,2):
    print(f"              ********Round {each_rounds + 1}****", end='')
print()

for player, each_rounds in zip(players_name, range(0,2) ):
   print(player,score.get(f'rounds_{each_rounds}').get(player))

当前输出

********Round 1****              ********Round 2****
jack 9
joe 13

期望输出

********Round 1****              ********Round 2****          *****Total*****
jack                 9                                  11                       20
joe                  8                                  13                       21                    

解决方案代码

score = {'rounds_0': {'jack': 9, 'joe': 8}, 'rounds_1': {'jack': 11, 'joe': 13}}
players_name = ["jack", "joe"]
round_count = 2

# 打印表头
print(f"              ********Round 1****              ********Round 2****          *****Total*****")

# 遍历每个玩家,输出各轮分数和总分
for player in players_name:
    # 收集该玩家每一轮的分数
    round_scores = [score[f'rounds_{i}'][player] for i in range(round_count)]
    total = sum(round_scores)
    # 按固定格式输出:玩家名左对齐,分数和总分右对齐,保证列对齐
    print(f"{player:<10} {round_scores[0]:>20} {round_scores[1]:>30} {total:>20}")

关键说明

  • 用列表推导式一次性收集玩家所有轮次的分数,解决原代码中zip导致的索引错位问题
  • 利用格式化字符串的对齐参数(<左对齐、>右对齐)和宽度设置,确保每列内容整齐对齐
  • 通过sum()直接计算总分,简化逻辑

内容的提问来源于stack exchange,提问作者astro geek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:10:28