以表格格式打印字典?

时间:2013-04-24 10:24:23

标签: python

我有一个类似的字典:

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

然后我按照这样排序:

zipped = zip(*((key, value) for key, value in sorted(band2.items(), 
                                             key= lambda x: int(x[0][7:]))))

这给出了这个结果:

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

我想知道如何以某种格式打印出来:

Channel 1 Channel 2 ...... Channel 12
value[0] value[0] ........value[0]
value[1]/value[2] value[1]/value[2].....value[1]/value[2]
value[3] value[3]...........value[3]

因此示例输出将是:

Channel 1 Channel 2  <other values> Channel 12
10564     10589      <other values>    10837
2112/1922 2117/1927  <other values>    2167/1977
20        0          <other values>    15

我不确定如何在一张整洁的表格中打印这个,我会使用格式吗?

2 个答案:

答案 0 :(得分:3)

你可以尝试pandas,它提供了一个很好的结构来处理表:

Pandas的DataFrame可以通过以下项目构建:

In [69]: import pandas as pd
In [70]: df = pd.DataFrame.from_items(sorted(band2.items(), key=lambda x: int(x[0][7:])))
In [71]: df = df.astype('string')

Concat第1行和第2行

In [72]: df.ix[1] = df.ix[1] + '/' + df.ix[2]
In [73]: df = df.ix[[0, 1, 3]] 

无索引打印

In [74]: print df.to_string(index=None)

  channel1   channel2   channel3   channel4   channel5   channel6   channel7   channel8   channel9  channel10  channel11  channel12
     10564      10589      10612      10637      10662      10687      10712      10737      10762      10787      10812      10837
 2112/1922  2117/1927  2122/1932  2127/1937  2132/1942  2137/1947  2142/1952  2147/1957  2152/1962  2157/1967  2162/1972  2167/1977
        20          0          0         26         32          0         26          0          0          0          0         15  

答案 1 :(得分:2)

我最终没有使用zipped

table = [[], [], [], []]
# We can't just sort the channel names because 'channel11' < 'channel2'
channel_numbers = []
for channel_name in band2.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]
    table[0].append('Channel %d' % channel_number)
    table[1].append(str(channel_data[0]))
    table[2].append('%s/%s' % (channel_data[1], channel_data[2]))
    table[3].append(str(channel_data[3]))

for line in table:
    print('\t'.join(line))

如果标签不能正常工作,请确定每个列的宽度并用空格填充:

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)
    column_width = max(cell_widths)
    for i in range(len(column)):
        cell = column[i]
        padded_cell = cell + ' '*(column_width-len(cell))
        table[i].append(padded_cell)

for line in table:
    # If tabs don't make the columns align properly, try iterating through
    # column in line, and padding it with the appropriate number of spaces.
    print(' '.join(line))