猿问

在 python 中使用 format 在列中打印 n 行

我想将 n 行打印到列中。列大小取决于每行中最长的数据。


我有类似的东西


data = [['abcdefghijk', 'b','c'],['121','313','5441256652'],['--','310','36']['642','65','10']]


并想把它变成


abcdefghijk    121           --     642

b              313           310    65

c              5441256652    36     10

每列的宽度是行中最长元素的长度 + 4


我知道对于这种情况我可以使用


row_format ='{:<15}{:<14}{:<7}{:<7}'

for v in zip(*data):

    print (row_format.format(*v))

但是,如何在不事先知道元素长度的情况下获得数据中 n 行的相同模式?


忽然笑
浏览 141回答 1
1回答

肥皂起泡泡

您可以动态构建row_format字符串:row_format = ''.join(f'{{:<{len(max(x, key=len)) + 4}}}' for x in data)for v in zip(*data):&nbsp; &nbsp; print (row_format.format(*v))比如这个数据data = [['a', 'bbbbbb', 'c'],&nbsp; &nbsp; &nbsp; &nbsp; ['121', '313', '0'],&nbsp; &nbsp; &nbsp; &nbsp; ['------', '310', '36'],&nbsp; &nbsp; &nbsp; &nbsp; ['3', '455', '5']]是这样打印的:a&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;121&nbsp; &nbsp; ------&nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp;&nbsp;bbbbbb&nbsp; &nbsp; 313&nbsp; &nbsp; 310&nbsp; &nbsp; &nbsp; &nbsp;455&nbsp; &nbsp;&nbsp;c&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; 36&nbsp; &nbsp; &nbsp; &nbsp; 5
随时随地看视频慕课网APP

相关分类

Python
我要回答