首页 > 解决方案 > Dividing a list into subsets according to a numeric array in Python

问题描述

I have a list with characters like so:

s = ['Y', 'U', 'U', 'N', 'U', 'U', 'N', 'N', 'N']

And the following array:

t = [2, 4, 3]

I would like to divide the list according to the array, such that each subset st[i] has len(t[i]). Result for this example should be:

st = [['Y', 'U'], ['U', 'N', 'U', 'U'], ['N', 'N', 'N']]

If array t was:

t = [5, 2, 2]

Then the result should be:

st = [['Y', 'U', 'U', 'N', 'U'], ['U', 'N'], ['N', 'N']]

Entries are s and t. I am trying by inserting two loops, one for list s and another one for array t. But it is not working. How can I implement this?

标签: pythonstringlistset

解决方案


You can create an iterator from s and use itertools.islice to slice the iterator according to the sizes in t:

from itertools import islice

i = iter(s)
[list(islice(i, l)) for l in t]

This returns:

[['Y', 'U'], ['U', 'N', 'U', 'U'], ['N', 'N', 'N']]

推荐阅读