我正在尝试将列表写入具有特定列数的行。例如,列出:
data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
我想用这样的格式写出来:
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0,
10.0,
我已经尝试了以下代码;但是,只能使其打印第一行:
strformat = ['{'+str(i)+':>5.1f},' for i in range(0,3)]
strformat = ''.join(strformat).lstrip().rstrip() + '\n'
print strformat.format(*[x for x in data])
提前致谢!
最佳答案
def chunks(seq, n):
# http://stackoverflow.com/a/312464/190597 (Ned Batchelder)
""" Yield successive n-sized chunks from seq."""
for i in xrange(0, len(seq), n):
yield seq[i:i + n]
data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
for row in chunks(data, 3):
print(', '.join(map(str, row)))
产量
1.0, 2.0, 3.0
4.0, 5.0, 6.0
7.0, 8.0, 9.0
10.0
或者,也许更接近您的代码:
strformat = '\n'.join(
', '.join('{:>5.1f}' for item in row)
for row in chunks(data, 3))
print(strformat.format(*data))