gpt4 book ai didi

python - 如何以所需的方式打印输出?

转载 作者:行者123 更新时间:2023-12-01 01:28:51 26 4
gpt4 key购买 nike

我希望按照期望的方式打印嵌套字典的输出,但没有任何想法来做同样的事情。任何人都可以帮忙解决此案吗?

#!/usr/bin/python

#Using python 2.7

li= [ {1: {"count_1": 12, "count_3": 899, "count_2": 100}},
{2: {"count_1": 13, "count_3": 100, "count_2": 200}},
{3: {"count_1": 14, "count_3": 999, "count_2": 300}},
{4: {"count_1": 15, "count_3": 99, "count_2": 400}}]

fmt = "{:} {:} {:} {:} {:} "
print fmt.format("name", "stat1", "stat2", "stat3", "stat4")

for dict_data in li:
for parent_key,value in dict_data.iteritems():
for k,v in value.iteritems():
print k, "->", v

获取输出为:

name, stat1  stat2  stat3   stat4  
count_3 -> 899
count_2 -> 100
count_1 -> 12
count_3 -> 100
count_2 -> 200
count_1 -> 13
count_3 -> 999
count_2 -> 300
count_1 -> 14
count_3 -> 99
count_2 -> 400
count_1 -> 15

预期输出:

    name       stat1  stat2  stat3   stat4  
count_3 899 100 999 99
count_2 100 200 300 400
count_1 12 13 14 15

使用:Python 2.7,我想避免pandas

最佳答案

这是一种方法。您可以提取“行名称”并首先对它们进行排序,因为每个行都在单独的行上,然后从 li 中提取每行的值:

fmt = "{:}\t{:}\t{:}\t{:}\t{:}  "
print(fmt.format("name", "stat1", "stat2", "stat3", "stat4"))

rows = sorted(li[0][1].keys(), reverse=True) # ['count_3', 'count_2', 'count_1']
for rname in rows:
stats = [val[rname] for d in li for val in d.values()]
print(fmt.format(rname, *stats))

输出

name    stat1   stat2   stat3   stat4                                                                                                                                              
count_3 899 100 999 99
count_2 100 200 300 400
count_1 12 13 14 15

关于python - 如何以所需的方式打印输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53089120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com