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
、そこからそれを把握できるはずです。