2

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.

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
Temir
  • 21
  • 2
  • 5
    If you edit your post to include your attempts, we'll be able to help you correct them – inspectorG4dget Jan 13 '23 at 21:30
  • You could do something along the lines of `start = 0` and `end = start + 1st element of B`, then retrieve `A[start:end]` ; then update `start = end` and do the same thing by iterating over elements of B; with a little research, this should be enough for you to produce working code. – Swifty Jan 13 '23 at 21:33
  • Does this answer your question? [Splitting a list into uneven groups?](https://stackoverflow.com/questions/38861457/splitting-a-list-into-uneven-groups) – DarrylG Jan 13 '23 at 21:39

4 Answers4

5

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()
wim
  • 338,267
  • 99
  • 616
  • 750
2
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]
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

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
TimbowSix
  • 342
  • 1
  • 7
1

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))]
Swifty
  • 2,630
  • 2
  • 3
  • 21