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