以Pythonic方式按字母顺序垂直打印元组元素
我有一个包含命名元组的列表,想要以一种容易阅读的方式打印出元组中的元素。这个列表的每一行大约有50个以上的命名元组元素。
namedtuple = ('apple', 'box', 'cat', 'dog', 'phone', 'elephant', 'horse', 'goose', 'frog')
期望的输出结果:
apple dog goose
box elephant horse
cat frog
3 个回答
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()
你打印的每一行其实就是原始元组的一部分,使用了合适的步长。
0
我之前用Python打印ASCII表格的时候,成功地使用了PrettyTable这个工具:https://code.google.com/p/prettytable/
至于排序,你只需要用内置的sorted()
函数,然后从元组中取出大小相等的一部分,最后把它们添加到PrettyTable对象里就可以了。
1
第一步:对这个元组进行排序。
sortedtuple = sorted(namedtuple)
第二步:把这个元组分成几列。
num_rows = (len(sortedtuple) + num_columns-1) // num_columns
columns = [sortedtuple[i*num_rows:(i+1)*num_rows] for i in range(num_columns)]
第三步:在最后一列后面加上空白,使它的大小和其他列一样。
columns[-1] = columns[-1] + ['']*(len(columns[0])-len(columns[-1]))
第四步:遍历一个把列合并在一起的列表,然后打印出来。
width = max(len(word) for word in sortedtuple)
for row in zip(*columns):
print ' '.join(word + ' '*(width- len(word)) for word in row)