Python嵌套字典打印时双位数值拆分换行问题及解决问询
问题原因
你代码中多了一层完全不必要的循环逻辑:player_statistics[player][stat_type] 取出的本身就是完整的统计值字符串(比如'14'、'11'),对字符串执行for循环迭代时,会逐个遍历每一位字符,每次调用print(value)默认会在结尾自动添加换行符,所以双位数值就会被拆成两行打印。代码中额外加的sorted()对字符串排序也属于多余逻辑,没有任何作用。
修复方案
直接删掉遍历value的那层循环,直接打印统计值即可,修改后的完整代码如下:
def main(): player_statistics = {'Johny': {'Kills': '7', 'Assists': '11', 'Deaths': '14'}, 'Alice': {'Kills': '5', 'Deaths': '7', 'Assists': '3'}, 'Jim': {'Kills': '14', 'Deaths': '6', 'Assists': '9'}} print("Player statistics:") print() for player in sorted(player_statistics): print(player.upper()) for stat_type in sorted(player_statistics[player]): print(f"{stat_type}: {player_statistics[player][stat_type]}") print("------------") if __name__ == "__main__": main()
运行上述代码即可得到你预期的输出格式。
内容的提问来源于stack exchange,提问作者strawberrycheesecake
相关产品推荐
相关产品推荐

