关于python:通过连接另一个列表的元素来创建字符串列表

Create a list of strings by joining elements of another list

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
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语句效率很低,因此我需要帮助。XYX


1
[' '.join(a[i:i+3]) for i in range(0, len(a), 3)]


重新使用!

1
2
3
4
5
6
7
8
9
10
11
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)]

主要是用这个。