Python遍历嵌套列表打印玩家数据 按指定模板格式化输出
原有代码问题
index1 += 1写在while循环外部,执行完内层循环才会运行,且循环终止条件绑定的是玩家列表总长度(共5个元素),全程只会读取第一个玩家(索引0)的前5项数据,既不会遍历其他玩家,也读不全单个玩家的全部属性- 索引逻辑颠倒:外层索引应该遍历玩家序号,内层索引遍历单个玩家的属性序号,原有代码把两层索引的边界和迭代逻辑完全写混了
实现代码
直接用for循环遍历嵌套列表是最简洁不易出错的方案,搭配f-string做对齐即可匹配要求的输出格式:
player_list = [['Bruce Wayne', 5, 5, 0, 0, 100, 15], ['Jessica Jones', 12, 0, 6, 6, 10, 6], ['Johnny Rose', 6, 2, 0, 4, 20, 10], ['Gina Linetti', 7, 4, 0, 3, 300, 15], ['Buster Bluth', 3, 0, 2, 1, 50, 1]] # 输出指定格式表头 print("=" * 60) print(f"-{'Player Summary':^58}-") print("=" * 60) print(f"-{'P W L D Chips Score':>58}-") # 遍历所有玩家,格式化输出 for player in player_list: name, p, w, l, d, chips, score = player print(f"- {name:<15}{p:>2} {w:>2} {l:>2} {d:>2} {chips:>6} {score:>6} -")
如果必须使用while循环实现,注意把两层索引的迭代逻辑放在对应循环的内部,参考写法:
player_list = [['Bruce Wayne', 5, 5, 0, 0, 100, 15], ['Jessica Jones', 12, 0, 6, 6, 10, 6], ['Johnny Rose', 6, 2, 0, 4, 20, 10], ['Gina Linetti', 7, 4, 0, 3, 300, 15], ['Buster Bluth', 3, 0, 2, 1, 50, 1]] # 输出指定格式表头 print("=" * 60) print(f"-{'Player Summary':^58}-") print("=" * 60) print(f"-{'P W L D Chips Score':>58}-") player_idx = 0 while player_idx < len(player_list): current = player_list[player_idx] name, p, w, l, d, chips, score = current print(f"- {name:<15}{p:>2} {w:>2} {l:>2} {d:>2} {chips:>6} {score:>6} -") player_idx += 1
运行后输出完全匹配要求的对齐格式,不会出现属性错位、遍历不全的问题。
内容的提问来源于stack exchange,提问作者Epilox
相关产品推荐
相关产品推荐

