如何在Python中将列表字典格式化为表?

2024-06-16 14:46:08 发布

您现在位置:Python中文网/ 问答频道 /正文

dic = {'S00:D58': 1, 'M23:Q14': 1, 'S43:H52': 84, 
       'S43:H53': 2, 'S43:H50': 5, 'S43:H57': 1, 'M87:E11': 10}

我想把它打印成3列的表格,比如:

S00         D58          1    
M23         Q14          1   
S43         H52          84   
S43         H53          2   
S43         H50          5   
S43         H57          1   
M87         E11          10 

有没有一个简单的方法来实现这一点?你知道吗


Tags: 方法表格dice11m23s43q14h53
3条回答

您可以使用ljust执行以下操作:

for k,v in dic.items():
    a,b = k.split(':')
    print a.ljust(30), b.ljust(30), v

将打印以下内容:

S00                            D58                            1
M23                            Q14                            1
S43                            H52                            84
S43                            H53                            2
S43                            H50                            5
S43                            H57                            1
M87                            E11                            10

doc

These functions respectively left-justify, right-justify and center a string in a field of given width. They return a string that is at least width characters wide, created by padding the string s with the character fillchar (default is a space) until the given width on the right, left or both sides. The string is never truncated.

请注意,还可以使用format来获得相同的效果:

print '{:<30s}{:<30s}{}'.format(a, b, v)

您还可以使用字符串格式化方法^{}

for k, v in dic.items():
    a, b = k.split(':')
    print '{:30s}{:30s}{}'.format(a, b, v)
>>> dic = {'S00:D58': 1, 'M23:Q14': 1, 'S43:H52': 84, 
       'S43:H53': 2, 'S43:H50': 5, 'S43:H57': 1, 'M87:E11': 10}
>>>
>>> output = '\n'.join(['{:<10} {:<10} {:<10}'.format(*k.split(':'), dic[k]) for k in dic])
>>> print(output)
S43        H52        84        
S43        H53        2         
S00        D58        1         
S43        H57        1         
M87        E11        10        
S43        H50        5         
M23        Q14        1       

相关问题 更多 >