>> col_size = {}>>> for row in d:for i, col in enumerat..._for i, col in enumerate(data_pic.columns):">
赞
踩
从您的输入数据开始:
>>> d = (
("row a", "a1","a2","a3"),
("another row", "b1"),
("c", "x", "y", "a long string")
)
进行一次通过以确定每列的最大大小:
>>> col_size = {}
>>> for row in d:
for i, col in enumerate(row):
col_size[i] = max(col_size.get(i, 0), len(col))
>>> ncols = len(col_size)
然后进行第二遍,将每列填充到所需的宽度:
>>> result = []
>>> for row in d:
row = list(row) + [''] * (ncols - len(row))
for i, col in enumerate(row):
row[i] = col.ljust(col_size[i])
result.append(row)
这给出了期望的结果:
>>> from pprint import pprint
>>> pprint(result)
[['row a ', 'a1', 'a2', 'a3 '],
['another row', 'b1', ' ', ' '],
['c ', 'x ', 'y ', 'a long string']]
为了方便起见,这些步骤可以组合成一个功能:
def align(array):
col_size = {}
for row in array:
for i, col in enumerate(row):
col_size[i] = max(col_size.get(i, 0), len(col))
ncols = len(col_size)
result = []
for row in array:
row = list(row) + [''] * (ncols - len(row))
for i, col in enumerate(row):
row[i] = col.ljust(col_size[i])
result.append(row)
return result
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。