>> col_size = {}>>> for row in d:for i, col in enumerat..._for i, col in enumerate(data_pic.columns):">
当前位置:   article > 正文

python规范化字符串_如何规范化python中的字符串列表?

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/204065?site
推荐阅读
相关标签
  

闽ICP备14008679号