格式化输出python

时间:2013-05-10 09:58:35

标签: python printing format

我有一些代码以某种格式打印字典。但是由于频道数量可能会有所不同,我想更改此格式。但我想知道它是否可以像我所拥有的那样轻松调整?这是代码:

band3={'channel11': [10812, 2162, 1972], 'channel10': [10787, 2157, 1967], 'channel3': [10612, 2122, 1932], 'channel2': [10589, 2117, 1927], 'channel1': [10564, 2112, 1922], 'channel7': [10712, 2142, 1952], 'channel6': [10687, 2137, 1947], 'channel5': [10662, 2132, 1942], 'channel4': [10637, 2127, 1937], 'channel9': [10762, 2152, 1962], 'channel8': [10737, 2147, 1957], 'channel12': [10837, 2167, 1977]}

table = [[], [], [], []]
# can't just sort the channel names because 'channel11' < 'channel2'
channel_numbers = []
for channel_name in band3.keys():
    if channel_name.startswith('channel'):
        channel_number = int(channel_name[7:])
        channel_numbers.append(channel_number)
    else:
        raise ValueError("channel name doesn't follow pattern")
channel_numbers.sort()

for channel_number in channel_numbers:
    channel_data = band2['channel%d' % channel_number]
    column =[
              'Channel %d' % channel_number,
               str(channel_data[0]),
               '%s/%s' % (channel_data[1], channel_data[2]),
               str(channel_data[3])
            ]
    cell_widths = map(len, column) #9 5 2 9
    column_widths = max(cell_widths) # 9 or 10
    for i in range(len(cell_widths)): #4
        cell = column[i]
        padded_cell = cell + ' '*(column_widths-len(cell))
        table[i].append(padded_cell)



print('{0} {1}'.format("".ljust(6), ' '.join(table[0])))   
print('{0} {1}'.format("UARFCN".ljust(6), ' '.join(table[1])))   
print('{0} {1}'.format("DL/UL".ljust(6), ' '.join(table[2])))   
print('{0} {1}'.format("RSSI".ljust(6), ' '.join(table[3])))        

目前是输出:

       Channel 1 Channel 2 Channel 3 Channel 4 Channel 5 Channel 6 Channel 7 Channel 8 Channel 9 Channel 10 Channel 11 Channel 12
UARFCN 10564     10589     10612     10637     10662     10687     10712     10737     10762     10787      10812      10837     
DL/UL  2112/1922 2117/1927 2122/1932 2127/1937 2132/1942 2137/1947 2142/1952 2147/1957 2152/1962 2157/1967  2162/1972  2167/1977 
RSSI   20        0         0         26        32        0         26        0         0         0          0          15     

我想改变它,而不是在一条长行上列出所有数据,以便在每4个元素之后,下一位数据打印在一个新行上。

       Channel 1 Channel 2 Channel 3 Channel 4
UARFCN 10564     10589     10612     10637       
DL/UL  2112/1922 2117/1927 2122/1932 2127/1937 
RSSI   20        0         0         26    

       Channel 5 Channel 6 Channel 7 Channel 8 
UARFCN 10662     10687     10712     10737         
DL/UL  2112/1922 2117/1927 2122/1932 2127/1937   
RSSI   32        0         26        0                 

       Channel 9 Channel 10 Channel 11 Channel 12       
UARFCN 10762     10787      10812      10837 
DL/UL  2132/1942 2137/1947 2142/1952 2147/1957 
RSSI   0         0          0          15

编辑Mar:

names = ["", "UARFCN", "DL/UL", "RSSI"]
lwidth = max(len(l) for l in names)
for i in range(0, len(table[0]), 4):
    for j, head in enumerate(names):
        print(' {0:<{lwidth}} {1}'.format(head, ' '.join(table[j][i:i+4])))
    print

2 个答案:

答案 0 :(得分:2)

您知道str.format()可以为您辩护吗?添加<6作为格式化字符串会让format左侧调整文本,使用空格以匹配6个字符:'{0:<6} {1}'。您可以对表'列'的其余部分执行相同的操作,包括使用可变宽度格式。

此外,您可以在格式中使用描述性命名,并使用一些序列索引来形成整行:

table_row = '{label:<{lwidth}} {row[0]:<{cwidth}} {row[1]:<{cwidth}} {row[2]:<{cwidth}} {row[3]:<{cwidth}}'

创建一个四列格式,其列宽为参数cwidth。我也使标签宽度变量,因此您可以稍后修改标签(添加更多,使用详细标签等)而不会破坏您的布局。

接下来,将每个标签的数据分组,以便于处理:

labels = ('', 'UARFCN', 'DL/UL', 'RSSI')
lwidth = max(len(l) for l in labels)
table = []

channel_numbers = [int(cname[7:]) if cname.startswith('channel') else None for cname in band3]
if None in channel_numbers:
    raise ValueError("channel name doesn't follow pattern")
channel_numbers.sort()

cwidth = 0
for channel_number in channel_numbers:
    channel_data = band2['channel{}'.format(channel_number)]
    entry = dict(zip(labels, (
        'Channel {}'.format(channel_number),
        channel_data[0],
        '{}/{}'.format(*channel_data[1:3]),
        channel_data[3]
    )))
    cwidth = max(cwidth, max(len(str(v)) for v in entry.values()))
    table.append(entry)

现在我们将列表中的表数据作为字典条目;以这种方式将它们分组更容易。接下来我们使用itertools grouper recipe

from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

# use a empty dictionary as filler at the end
for group in grouper(table, 4, dict.fromkeys(labels, '')):
    for label in labels:
        print(table_row.format(label=label, cwidth=cwidth, lwidth=lwidth,
            row=[entry[label] for entry in group]))
    print()

然后输出(使用重建的band2band3输入):

       Channel 1  Channel 2  Channel 3  Channel 4 
UARFCN 10564      10589      10612      10637     
DL/UL  2112/1922  2117/1927  2122/1932  2127/1937 
RSSI   20         0          0          26        

       Channel 5  Channel 6  Channel 7  Channel 8 
UARFCN 10662      10687      10712      10737     
DL/UL  2132/1942  2137/1947  2142/1952  2147/1957 
RSSI   32         0          26         0         

       Channel 9  Channel 10 Channel 11 Channel 12
UARFCN 10762      10787      10812      10837     
DL/UL  2152/1962  2157/1967  2162/1972  2167/1977 
RSSI   0          0          0          15        

dict.fromkeys(labels, '')默认值确保如果表中有一行少于4个条目,则最后一列用空字符串填充:

       Channel 1  Channel 2  Channel 3  Channel 4 
UARFCN 10564      10589      10612      10637     
DL/UL  2112/1922  2117/1927  2122/1932  2127/1937 
RSSI   20         0          0          26        

       Channel 5  Channel 6  Channel 7  Channel 8 
UARFCN 10662      10687      10712      10737     
DL/UL  2132/1942  2137/1947  2142/1952  2147/1957 
RSSI   32         0          26         0         

       Channel 9  Channel 10 Channel 11           
UARFCN 10762      10787      10812                
DL/UL  2152/1962  2157/1967  2162/1972            
RSSI   0          0          0                    

答案 1 :(得分:1)

names = ["", "UARFCN", "DL/UL", "RSSI"]
for i in range(0, len(table[0]), 4):
    for j, head in enumerate(names):
        print('{0} {1}'.format(head.ljust(6), ' '.join(table[j][i:i+4])) )
    print()