如何使用python在x列表列表中拆分一个列表?

How to split one list in a list of x list with python?

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

如何在python中拆分x列表列表中的列表?

例如,列表分为两个列表:

1
2
elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-> ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])

示例:列表分为3个列表(注意第三个元组列表,包含"division rest"):

1
2
elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-> ([0, 1, 2], [3, 4, 5], [6, 7, 8, 9])

等。。。


您可以这样尝试:

编辑2:

1
2
3
4
5
6
7
8
9
i,j,x=len(seq),0,[]

for k in range(m):

    a, j = j, j + (i+k)//m

    x.append(seq[a:j])

return x

像呼叫

1
seq = range(11), m=3

结果

1
result : [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
1
2
def chunks(l, n):
    return [l[i:i + n] for i in range(0, len(l), n)]

Eddi1:

1
2
3
>>> x = [1,2,3,4,5,6,7,8,9]
>>> zip(*[iter(x)]*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]


1
2
3
4
5
6
7
8
9
10
def chunk(iterable ,n):
    le = len(iterable)
    if n > le:
        return  iterable
    mo = le % n # get mod from length of the iterable % required len sublists
    diff = le - mo #  if there was any mod, i.e 10 % 3 = 1, diff will be 9
    sli = le / n
    res = [iterable[ind:ind + sli] for ind in range(0, diff, sli)]
    res[-1] = res[-1] + iterable[diff:] # add from diff to end of the last sublist
    return tuple(res) # return a tuple lists

如果mo = le % n == 0diff等于列表的长度,那么iterable[diff:]将不添加任何内容。