将列表写入到具有特定列数的行中 [英] Write to list to rows with specific number of columns
本文介绍了将列表写入到具有特定列数的行中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将列表写入具有特定列数的行。例如,可以列出:
I'm trying to write a list to rows with a specific number of columns. For example, take the list:
data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
我想用这样的格式写出来: / p>
I would like to write this out with a format such that it looks like:
1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0,
10.0,
我试过了下面的代码;但是,只能打印第一行:
I've tried the following code; however, can only get it to print the first line:
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)))
$ b $
yields
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))
这篇关于将列表写入到具有特定列数的行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文