0

我有一些代码可以以某种格式打印字典。但是,由于频道数量可能会有所不同,因此我想更改此格式。但我想知道它是否可以作为我所拥有的简单调整来完成?这是代码:

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

编辑三月:

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
4

2 回答 2

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配方

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                    
于 2013-05-10T10:23:39.793 回答
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()
于 2013-05-10T10:01:26.353 回答