纵向打印字典,横向打印嵌套列表
Printing Dictionary in Vertical, and nested List in Horizontal
如何在保持缩进的情况下水平显示列表(嵌套在字典中)?如果我只使用 print()
,则缺少缩进。
尝试了下面的代码,但是缺少缩进。
for key, value in new_pd_dict.items():
print("%s: %s" % (key, value))
没有内置的 python 库可以执行此操作。但你可以这样做:
my_dict = {"x": [1, 2, 3],
"y": [4, 5, 6],
"z": [7, 8, 9]}
for key, value in my_dict.items():
print("%s: %s" % (key, value))
这段简短的代码将在控制台中产生如下内容:
y: [4, 5, 6]
x: [1, 2, 3]
z: [7, 8, 9]
您可以尝试将参数传递给 pprint
,例如 compact=True
。
来自 documentation,“如果 compact 为真,则将在每个输出行上格式化适合宽度的项目”
>>> pprint.pprint(new_pd_dict, compact=True)
{'Attack': [41, 87, 9, 38, 35, 30, 59, 98, 44, 9, 97, 53, 10, 79, 97, 46, 59,
82, 75, 13, 72, 51, 80, 75, 80, 94, 88, 36, 76, 3, 32, 85, 95, 74,
22, 28, 71, 57, 94, 29, 81, 89, 80, 42, 55, 7, 69, 3, 46, 40, 73,
76, 41, 14, 47, 31, 45, 5, 78, 59, 4, 44, 4, 73, 9, 76, 60, 60, 16,
2, 85, 6, 28, 21, 98, 1, 54, 24, 5, 1, 61, 39, 58, 26, 67, 52, 34,
46, 23, 68, 25, 63, 36, 49, 66, 24, 2, 39, 15, 12]}
您还可以在函数调用中使用 width=<number>
调整宽度(默认为 80)。
如何在保持缩进的情况下水平显示列表(嵌套在字典中)?如果我只使用 print()
,则缺少缩进。
尝试了下面的代码,但是缺少缩进。
for key, value in new_pd_dict.items():
print("%s: %s" % (key, value))
没有内置的 python 库可以执行此操作。但你可以这样做:
my_dict = {"x": [1, 2, 3],
"y": [4, 5, 6],
"z": [7, 8, 9]}
for key, value in my_dict.items():
print("%s: %s" % (key, value))
这段简短的代码将在控制台中产生如下内容:
y: [4, 5, 6]
x: [1, 2, 3]
z: [7, 8, 9]
您可以尝试将参数传递给 pprint
,例如 compact=True
。
来自 documentation,“如果 compact 为真,则将在每个输出行上格式化适合宽度的项目”
>>> pprint.pprint(new_pd_dict, compact=True)
{'Attack': [41, 87, 9, 38, 35, 30, 59, 98, 44, 9, 97, 53, 10, 79, 97, 46, 59,
82, 75, 13, 72, 51, 80, 75, 80, 94, 88, 36, 76, 3, 32, 85, 95, 74,
22, 28, 71, 57, 94, 29, 81, 89, 80, 42, 55, 7, 69, 3, 46, 40, 73,
76, 41, 14, 47, 31, 45, 5, 78, 59, 4, 44, 4, 73, 9, 76, 60, 60, 16,
2, 85, 6, 28, 21, 98, 1, 54, 24, 5, 1, 61, 39, 58, 26, 67, 52, 34,
46, 23, 68, 25, 63, 36, 49, 66, 24, 2, 39, 15, 12]}
您还可以在函数调用中使用 width=<number>
调整宽度(默认为 80)。