如何将列表格式化为具有一定数量项的行?

时间:2019-02-08 21:46:04

标签: python formatting output

我在将列表格式化为格式化的输出时遇到问题,每行包含五个元素,但是我被卡住了。

words = ["letter", "good", "course", "land", "car", "tea", "speaker",\
         "music", "length", "apple", "cash", "floor", "dance", "rice",\
         "bow", "peach", "cook", "hot", "none", "word", "happy", "apple",\
         "monitor", "light", "access"]

输出:

letter good course land car
tea speaker music length apple
cash floor dance rice bow
peach cook hot none word
happy apple monitor light access

2 个答案:

答案 0 :(得分:2)

尝试一下:

>>> for i in range(0, len(words), 5):
...     print ' '.join(words[i:(i+5)])
... 
letter good course land car
tea speaker music length apple
cash floor dance rice bow
peach cook hot none word
happy apple monitor light access

答案 1 :(得分:1)

使用列表理解

num=5
[' '.join(words[i:i+num]) for i in range(0,len(words),num)]

也可以使用chunked,但可能必须先安装more_itertools

from more_itertools import chunked
list(chunked(words, 5))