def columnify(iterable):
# First convert everything to its repr
strings = [repr(x) for x in iterable]
# Now pad all the strings to match the widest
widest = max(len(x) for x in strings)
padded = [x.ljust(widest) for x in strings]
return padded
现在您应该能够使用pprint.pprint(compact=True)
, 或textwrap
, 或其他工具来获得所需的格式。
但是如果你想手动做,做任何你想做的事情都不是太难。例如:
def colprint(iterable, width=72):
columns = columnify(iterable)
colwidth = len(columns[0])+2
perline = (width-4) // colwidth
print('[ ', end='')
for i, column in enumerate(columns):
print(column, end=', ')
if i % perline == perline-1:
print('\n ', end='')
print(' ]')
所以:
>>> arr = ['a', 'b', 'cdefg', 'jk', 'lmnopqr', 'st', 'uv', 'wxyz', 1, 2, 3, 4]
>>> colprint(arr, 60)
[ 'a' , 'b' , 'cdefg' , 'jk' , 'lmnopqr',
'st' , 'uv' , 'wxyz' , 1 , 2 ,
3 , 4 , ]
这仍然不会为您提供确切的ls
功能;例如,ls
有一些启发式方法试图确保“太长”的文件名不计入最大宽度,而是跨越多列。如果你真的想把所有的东西都做的一模一样ls
,你可能需要查看源代码并从 C 翻译成 Python……</p>
另外,看看pprint
。每当一个模块的文档以指向源代码的链接开始时,这意味着该模块旨在用作有用的示例代码,并且它本身也是有用的。因此,如果您想查看它用于确定何时分割线的规则(基于compact
标志和宽度),您应该能够从那里弄清楚。