tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
这是我希望它看起来像
苹果爱丽丝狗开
橘子鲍勃猫
樱桃卡罗尔驼鹿
香蕉大卫鹅
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
这是我希望它看起来像
苹果爱丽丝狗开
橘子鲍勃猫
樱桃卡罗尔驼鹿
香蕉大卫鹅
移调和使用str.join:
print("\n".join(" ".join(t) for t in zip(*tableData)))
输出:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
zip(*tableData)
调换的数据:
[('apples', 'Alice', 'dogs'), ('oranges', 'Bob', 'cats'), ('cherries', 'Carol', 'moose'), ('banana', 'David', 'goose')]
然后,我们只是加入从由分离的每个元组中的元素一个空格并使用换行符作为分隔符来加入结果。
使用python3使用可以使用sep
:
print(*(" ".join(t) for t in zip(*tableData)), sep="\n")
虽然没有提供完全相同的输出,你可能有兴趣,看看如何csvkit
处理绘制表格:
https://github.com/onyxfish/csvkit/blob/master/csvkit/utilities/csvlook.py#L40
您可以修改根据需要(例如,如果不需要,则删除所有边界)。说干就干,做到了迅速给您:
import sys
def draw_table(rows):
widths = []
# Calculate the width of each column
for row in rows:
for i, v in enumerate(row):
try:
if len(v) > widths[i]:
widths[i] = len(v)
except IndexError:
widths.append(len(v))
for i, row in enumerate(rows):
for j, d in enumerate(row):
if d is None:
d = ''
sys.stdout.write(d.ljust(widths[j] + 1))
sys.stdout..write('\n')
然后,您可以只通过表格数据:
> draw_table(table_data)
apples oranges cherries banana
Alice Bob Carol David
dogs cats moose goose