Home > OS >  Splitting list into lists based on number in another list
Splitting list into lists based on number in another list

Time:01-14

Let's say I have two lists:

A = [15,2,3,42,5,6,7,82,94,12,1,21,2,3,4,5,5,3,2,2,22,3,4,5,6,6,5........]  # len(A) = 65
B = [15, 20, 4, 11, 12, 3]

As you can see the sum of numbers in list B is equal to 65 which is also length of list A.

What I want to do is that splitting list A into lists based on numbers in list B such as first list of lists contains 15 elements, second one 20, third one 4 and etc. I am waiting for your answers. Thanks in advance.

I tried some things but could not achieve what I want.

CodePudding user response:

You can use some handy pieces from itertools for this:

from itertools import pairwise, accumulate
from operator import add
A_split = [A[i:j] for i, j in pairwise(accumulate([0]   B, add))]

If you don't want to use itertools for whatever reason, it is also simple with a plain old for-loop:

A_split = []
for n in reversed(B):
    A_split.append(A[-n:])
    del A[-n:]
A_split.reverse()

CodePudding user response:

In [122]: A = list(range(1,66))

In [123]: len(A)
Out[123]: 65

In [124]: B = [15, 20, 4, 11, 12, 3]

In [125]: answer = []

In [126]: for b in B:
     ...:     answer.append(A[:b])
     ...:     A = A[b:]
     ...:

In [127]: for a in answer:
     ...:     print(len(a), a)
     ...:
15 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
20 [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
4 [36, 37, 38, 39]
11 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
12 [51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62]
3 [63, 64, 65]

CodePudding user response:

Using slicing to slice the desired chunk of A. Saving the resulting slice in result

result = []
latest = 0
for number in B:
    result.append(A[latest:latest number])
    latest  = number

CodePudding user response:

Oh well, just for the sake of it, here's a one-liner that does the job:

C = [A[sum(B[:i]):sum(B[:i 1])] for i in range(len(B))]

CodePudding user response:

Give Http://chat.openai.com a try

If you formulate your question correct it will probably give you a correct answer.

I was surprised to see how well it worked

  • Related