Python中的字符串格式,带有可变数字参数

时间:2018-01-03 07:44:15

标签: python string python-3.x dictionary format

我有dict,看起来像

A = {
    'test1':{'q0':[0.123,0.234],'phi0':[0.124,0.4325],'m':[9.42,0.3413]},
    'test2':{'q0':[0.343,0.353],'phi0':[0.2341,0.235]},
    'test3':{'q0':[0.343,0.353],'phi0':[0.2341,0.235],'m':[0.325,0.325],'z0':[0.234,0.314]}
    }

我想打印每个字典:

'test1':                 q0=0.123(0.234) phi0=0.123(0.4325) m=9.42(0.3413)
'test2':                 q0=0.343(0.353) phi0=0.2341(0.235)
'test3': z0=0.234(0.314) q0=0.343(0.353) phi0=0.2341(0.235) m=0.325(0.325)

如何使用string.format()在Python 3中执行此操作?由于每个子词典都有可变数量的参数,我不知道如何使用一些列表/词典理解来完成它。另外,如果我想留下一些空间,如果该参数缺失如图所示,我该怎么做?每个字典最多有五个不同的参数(q0,phi0,m,c,z0)。我把它打印到终端上,所以我不需要非常花哨的东西,但我希望它更容易阅读。

6 个答案:

答案 0 :(得分:5)

请注意,词典是无序的数据结构,因此除非您使用其有序的等效collections.OrderedDict(),否则您不能指望打印项目的任何顺序。不过,您可以在str.join()方法中使用生成器表达式:

In [4]: for key, value in A.items():
    print(','.join(("{}: {}={}({})".format(key, t1,t2,t3) for t1, (t2, t3) in value.items())))
   ...:     
test1: q0=0.123(0.234),test1: phi0=0.124(0.4325),test1: m=9.42(0.3413)
test3: q0=0.343(0.353),test3: phi0=0.2341(0.235),test3: m=0.325(0.325),test3: z0=0.234(0.314)
test2: q0=0.343(0.353),test2: phi0=0.2341(0.235)

另请注意,由于我们正在执行以下内联解包,如果列表中的项目数量多于/少于两个,则可能会引发ValueError。

for t1, (t2, t3) in value.items()

因此,请确保解包变量的数量与列表中的项目数相匹配。

答案 1 :(得分:1)

检查子词典的键中是否有'z0',对于那些项目,应用稍微不同的字符串操作,而不是那些没有该键的字符串操作。看起来有点脏,但确切地产生你的输出:

for k,v in A.items():
    if 'z0' in v:
        print (k,":","{}={}({})".format('z0',v['z0'][0],v['z0'][1]), " ".join("{}={}({})".format(e,t[0],t[1]) for e,t in v.items() if 'z0' not in e))
    else:
        print (k,":                "," ".join("{}={}({})".format(e,t[0],t[1]) for e,t in v.items()))

结果:

test1 :                 q0=0.123(0.234) phi0=0.124(0.4325) m=9.42(0.3413)
test2 :                 q0=0.343(0.353) phi0=0.2341(0.235)
test3 : z0=0.234(0.314) q0=0.343(0.353) phi0=0.2341(0.235) m=0.325(0.325)

注意:如果您确实需要test周围的单引号,即'test1'而不是test1,则可以在"'"的左侧和右侧添加k在我的两个print陈述中{1}}:print ("'",k,"'",...

答案 2 :(得分:1)

使用嵌套循环:

for m,x in A.items():
    for y,z in x.items():
        print(m,'{0}='.format(y), z[0],'({0})'.format(z[1]))

答案 3 :(得分:1)

由于您的测试和参数都在字典中,您可以先对它们进行排序以确保一致的排序。简单排序可能不起作用,但好像你有test13,默认情况下会出现在test1之后。您可以使用Python库natsort来帮助解决这个问题。

由于每组参数都可能缺少值,因此可以使用快速搜索来创建所需的所有cols的列表。然后,您可以在打印缺少值的行时保留空间:

from natsort import natsorted

A = {
    'test1':{'q0':[0.123,0.234],'phi0':[0.124,0.4325],'m':[9.42,0.3413]},
    'test2':{'q0':[0.343,0.353],'phi0':[0.2341,0.235]},
    'test3':{'q0':[0.343,0.353],'phi0':[0.2341,0.235],'m':[0.325,0.325],'z0':[0.234,0.314]},
    'test13':{'q0':[0.343,0.353],'z0':[0.234,0.314]}
    }

sorted_tests = natsorted(A.items())     # Ensure test13 is numerical sorted correctly
# Create a list of all required cols
cols = set()

for test, params in sorted_tests:
    cols.update(params.keys())

cols = sorted(cols)    

for test, params in sorted_tests:
    row = [(col, params.get(col, [])) for col in cols]
    cells = []
    for p, values in row:
        if values:
            cells.append('{:20}'.format('{}={}({})'.format(p, values[0], values[1])))
        else:
            cells.append('{:20}'.format(''))

    print("{:6} : {}".format('{}'.format(test), ''.join(cells)))

这会给你以下输出:

test1  : m=9.42(0.3413)      phi0=0.124(0.4325)  q0=0.123(0.234)                         
test2  :                     phi0=0.2341(0.235)  q0=0.343(0.353)                         
test3  : m=0.325(0.325)      phi0=0.2341(0.235)  q0=0.343(0.353)     z0=0.234(0.314)     
test13 :                                         q0=0.343(0.353)     z0=0.234(0.314)

答案 4 :(得分:0)

尝试使用基于for循环的代码生成排序输出:

outlist = []
for a in A:
    outstr = a+":"
    for aa in ('z0', 'q0','phi0','m','c'):
        if aa in A[a]:
            outstr += aa+"="+str(A[a][aa][0])+"("+str(A[a][aa][1])+") "
        else:
            outstr += "                "
    outlist.append(outstr)

for i in sorted(outlist):
    print(i)

输出:

test1:                q0=0.123(0.234) phi0=0.124(0.4325) m=9.42(0.3413)                 
test2:                q0=0.343(0.353) phi0=0.2341(0.235)                                 
test3:z0=0.234(0.314) q0=0.343(0.353) phi0=0.2341(0.235) m=0.325(0.325)          

答案 5 :(得分:0)

试试这个: -

A = {
    'test1':{'q0':[0.123,0.234],'phi0':[0.124,0.4325],'m':[9.42,0.3413]},
    'test2':{'q0':[0.343,0.353],'phi0':[0.2341,0.235]},
    'test3':{'q0':[0.343,0.353],'phi0':[0.2341,0.235],'m':[0.325,0.325],'z0':[0.234,0.314]}
    }
for i,j in A.items():
    print i+':',
    for x,y in j.items():
        print "{}= {}({})".format(x,y[0],y[1]),
    print 
#output is same as expected