2

I have a list of strings - foo and another list of integers- bar which keeps the track of important indices in foo.

For example:

foo = [{}.format(i) for i in range(1, 11)] # not necessarily of this format
bar = [0, 3, 5]

I would like to create a recipe for creating a list of lists, each list obtained by splitting foo based on indices in bar.

Expected output for the above example:

[['1', '2', '3'], ['4', '5'], ['6', '7', '8', '9', '10']]

For achieving this, I have created the following function which works fine:

result = []
for index, value in enumerate(b):
    if index == len(b) - 1:
        result.append(a[value:])
    elif index == 0 and value != 0:
        result.append(a[0: value])
    else:
        result.append(a[value: b[index + 1]])

However, I find this code highly Non-Pythonic, thanks to my C-Java background.
I would like to know a better solution to this problem (maybe we can use itertools somehow).

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71

2 Answers2

2

You could do as follows:

In [3]: [foo[a:b] for a, b in zip(bar, bar[1:]+[None])]
Out[3]: [['1', '2', '3'], ['4', '5'], ['6', '7', '8', '9', '10']]
J. P. Petersen
  • 4,871
  • 4
  • 33
  • 33
1

Here is one way using a list comprehension:

In [107]: bar = bar + [len(foo)] if bar[-1] < len(foo) else bar


In [110]: [foo[i:j] for i, j in zip(bar, bar[1:])]
Out[110]: [['1', '2', '3'], ['4', '5'], ['6', '7', '8', '9', '10']]
Mazdak
  • 105,000
  • 18
  • 159
  • 188