Python使用字典按指定格式输出列表对应记录数的问题解决
错误原因
- 循环时没有正确取字典的映射值做输出:如果直接用字典键的话会输出
Yellow_List这类不符合要求的内容,即使取了映射值,也因为嵌套循环导致内容交叉重复。 - 实际运行时写了双层嵌套循环:外层遍历3个列表名,内层遍历3个长度值,最终输出3×3=9行的重复内容,没有将列表名和对应长度做一一绑定。
- 没有按顺序配对两个序列的元素。
修复代码
如果你的no_of_records是按「黄→蓝→红」顺序存储的三个实际数据列表(之前输出的200/150/2000就是遍历该列表逐个取长度得到的),直接用zip配对映射值和长度即可:
list_names = { "Yellow_List": "yellow", "Blue_List": "blue", "Red_List": "red" } # 去掉嵌套循环,直接一一配对 for color_name, data in zip(list_names.values(), no_of_records): print(f"The {color_name} list has {len(data)}")
如果是手动维护长度列表,对应改成:
# 长度顺序和字典映射的颜色名顺序一致 record_lengths = [200, 150, 2000] for color_name, length in zip(list_names.values(), record_lengths): print("The", color_name, "list has", length)
运行效果
The yellow list has 200 The blue list has 150 The red list has 2000
如果使用低于3.7版本的Python,字典无序会导致顺序错乱,此时可以直接把颜色名做成有序列表:
color_names = ["yellow", "blue", "red"] record_lengths = [200, 150, 2000] for color_name, length in zip(color_names, record_lengths): print("The", color_name, "list has", length)
内容的提问来源于stack exchange,提问作者Girl007
相关产品推荐
相关产品推荐

