Skip to content Skip to sidebar Skip to footer

How To Split One List In A List Of X List With Python?

How to split a list in a list of x lists in python ? Exemple with list splited in 2 lists: elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -> ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9]) Exemp

Solution 1:

You may try like this:

EDIT2:-

i,j,x=len(seq),0,[]

for k in range(m):

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

    x.append(seq[a:j])

returnx

Call like

seq = range(11), m=3

Result

result : [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]


defchunks(l, n):
    return [l[i:i + n] for i inrange(0, len(l), n)]

EDIT1:-

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

Solution 2:

def chunk(iterable ,n):
    le = len(iterable)
    if n > le:
        returniterable
    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 sublistreturn tuple(res) # return a tuple lists

If mo = le % n == 0 diff will be equal to the length of the list so iterable[diff:] will add nothing.

Post a Comment for "How To Split One List In A List Of X List With Python?"