在打印列表中的项目时,我遇到了保持某种格式的问题:
[TEXT1, TEXT2, TEXT3, TEXT4, TEXT5, TEXT6, TEXT7, TEXT8, TEXT9]
预期输出:('〜'代表文档中的空白)
~~~~~~~~~~TEXT1, TEXT2, TEXT3, TEXT4, TEXT5,
~~~~~~~~~~TEXT6, TEXT7, TEXT8, TEXT9
我遇到的问题是在TEXT2
之后追加TEXT1
,而没有重新添加空格('〜')。
a = ['A121', 'A221', 'A321', 'A421', 'A521', 'A621', 'A721', 'A821', 'A921']
for v in a:
counter = 0
if counter == 5:
print '\n'
print " {},".format(v.ljust(0)),
输出:
A121 A221 A321 A421 A521 A621 A721 A821 A921
预期输出:
A121, A221, A321, A421, A521,
A621, A721, A821, A921
答案 0 :(得分:2)
有很多方法可以解决此问题:
一个:
a = ['A121', 'A221', 'A321', 'A421', 'A521', 'A621', 'A721', 'A821', 'A921']
INDENT = ' '*10
NUMBER_OF_COLUMNS = 5
lead = INDENT
for item_number, item in enumerate(a):
print("{lead}{item}".format(lead=lead, item=item), end='')
if item_number % NUMBER_OF_COLUMNS == NUMBER_OF_COLUMNS - 1:
lead = ",\n" + INDENT
else:
lead = ", "
两个:
table = []
row = []
for item in a:
row.append(item)
if len(row) == NUMBER_OF_COLUMNS:
table.append(INDENT + ', '.join(row))
row = []
table.append(INDENT + ', '.join(row))
print(',\n'.join(table))
三个,单线:
print(',\n'.join(INDENT + ', '.join(a[i:i + NUMBER_OR_COLUMNS]) for i in range(0, len(a), NUMBER_OR_COLUMNS)))
或者也许textwrap.fill()可以工作:
from textwrap import fill
print(fill(', '.join(a), initial_indent=10*' ', subsequent_indent=10*' ', width=40))
所有输出(示例中显示逗号):
A121, A221, A321, A421, A521,
A621, A721, A821, A921
答案 1 :(得分:1)
这是一种相当通用,简洁有效的方法:
import textwrap
from itertools import zip_longest
def grouper(n, iterable, _SENTINEL=object()):
""" Collect data into fixed-length chunks or blocks. """
args = [iter(iterable)] * n
for t in zip_longest(*args, fillvalue=_SENTINEL):
yield list(elem for elem in t if elem is not _SENTINEL)
def text_wrap(words, numcols, indent=0):
lines = (' '.join(group) for group in grouper(numcols, words))
return textwrap.indent('\n'.join(lines), indent*' ')
if __name__ == '__main__':
a = 'A121', 'A221', 'A321', 'A421', 'A521', 'A621', 'A721', 'A821', 'A921'
lines = text_wrap(a, 5, 8)
print(lines)
输出:
A121 A221 A321 A421 A521
A621 A721 A821 A921