Pythonic方式垂直和按字母顺序打印元组元素

时间:2014-04-16 18:57:06

标签: python

我有一个namedtuples列表,希望能够以某种方式打印元组的元素,以便于阅读。列表的每一行包含大约50多个namedtuple元素。

namedtuple = ('apple', 'box', 'cat', 'dog', 'phone', 'elephant', 'horse', 'goose', 'frog')

期望的输出:

apple   dog        goose 
box     elephant   horse
cat     frog

3 个答案:

答案 0 :(得分:1)

第1步:对元组进行排序。

sortedtuple = sorted(namedtuple)

第2步:将元组分成列。

num_rows = (len(sortedtuple) + num_columns-1) // num_columns
columns = [sortedtuple[i*num_rows:(i+1)*num_rows] for i in range(num_columns)]

步骤3:使用空白扩展最后一列,使其与其他列的大小相同。

columns[-1] = columns[-1] + ['']*(len(columns[0])-len(columns[-1]))

步骤4:遍历压缩的列列表并打印它们。

width = max(len(word) for word in sortedtuple)
for row in zip(*columns):
    print '  '.join(word + ' '*(width- len(word)) for word in row)

答案 1 :(得分:0)

为了使用Python打印ASCII表,我前段时间使用了PrettyTable并取得了成功:https://code.google.com/p/prettytable/

关于排序,只需使用内置的sorted()函数;然后从元组中取出相等大小的切片,并将它们添加到PrettyTable对象中。

答案 2 :(得分:0)

一种简单的方法(Python 3 - 你没有指定2.x或3.x),其中columns是所需的列数:

def print_in_columns(values, columns):
  values = sorted(values) # for alphabetical order
  column_width = max(len(s) for s in values) + 2 # you could pick this explicitly
  rows = (len(values) + columns - 1) // columns # rounding up
  format = "{:" + str(column_width) + "}"
  for row in range(rows):
    for value in values[row::rows]:
      print(format.format(value), end="")
    print()

您打印的每一行只是原始元组的一部分,具有正确的步长值。