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

Phy*_*ist 1 python string format dictionary python-3.x

我有一个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]}
    }
Run Code Online (Sandbox Code Playgroud)

我想打印每个字典:

'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)
Run Code Online (Sandbox Code Playgroud)

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

Kas*_*mvd 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)
Run Code Online (Sandbox Code Playgroud)

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

for t1, (t2, t3) in value.items()
Run Code Online (Sandbox Code Playgroud)

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