2

Apologies for any confusion in the explanation below, but I'm a little new to Python.

I have a list of text, and I would like to chunk the list up into larger pieces based on a separate list of values.

For example:

lst_a = ['This', 'is', 'an', 'example', 'of', 'a', 'simple', 'English', 'sentence.']
lst_b = [3, 4, 2]

Desired Result:

new_lst_a = ['This is an', 'example of a simple', 'English sentence.']

Any help/direction is greatly appreciated!

teddygraham
  • 117
  • 7

3 Answers3

4

Something like this using slices:

lst_a = ['This', 'is', 'an', 'example', 'of', 'a', 'simple', 'English', 'sentence.']
lst_b = [3, 4, 2]
new_list = []

index = 0
for n in lst_b:
    new_list.append(' '.join(lst_a[index:index + n]))
    index += n

print(new_list)

Output:

['This is an', 'example of a simple', 'English sentence.']
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
salvicode
  • 227
  • 2
  • 12
2

If you write a simple for-loop you can consume an iterator of the original list. This approach makes no unnecessary copies.

>>> result = []
>>> it = iter(lst_a)
>>> for n in lst_b:
...     s = " ".join(next(it) for i in range(n))
...     result.append(s)
...
>>> result
['This is an', 'example of a simple', 'English sentence.']
wim
  • 338,267
  • 99
  • 616
  • 750
0

You can use islice to do this easily by grabbing n elements at a time

>>> from itertools import islice
>>> lst_a = ['This', 'is', 'an', 'example', 'of', 'a', 'simple', 'English', 'sentence.']
>>> lst_b = [3, 4, 2]
>>> 
>>> itr = iter(lst_a)
>>> [' '.join(islice(itr, n)) for n in lst_b]
['This is an', 'example of a simple', 'English sentence.']
Prem Anand
  • 2,469
  • 16
  • 16