可能重复:
How do you split a list into evenly sized chunks in Python?
Merge two lists in python?
数组中的原始数据:
a = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
期望的输出:
['1 2 3', '4 5 6', '7 8 9']
我知道使用while
语句是低效的,所以我需要帮助。 X_X
答案 0 :(得分:17)
[' '.join(a[i:i+3]) for i in range(0, len(a), 3)]
答案 1 :(得分:3)
重用!
from itertools import islice
def split_every(n, iterable):
i = iter(iterable)
piece = list(islice(i, n))
while piece:
yield piece
piece = list(islice(i, n))
a = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
new_a = [' '.join(slice) for slice in split_every(3, a)]
主要使用this。