Bill Chung Bill Chung - 2 months ago 16
Python Question

slice a list based on some values

Hi I'm looking for a way to split a list based on some values, and assuming the list's length equals to sum of some values, e.g.:

list:

l = ['a','b','c','d','e','f']

values:
v = (1,1,2,2)

so
len(l) = sum(v)


and I'd like to have a function to return a tuple or a list, like:
(['a'], ['b'], ['c','d'], ['d','e'])


currently my code is like:

(list1,list2,list3,list4) = (
l[0:v[0]],
l[v[0]:v[0]+v[1]],
l[v[0]+v[1]:v[0]+v[1]+v[2]],
l[v[0]+v[1]+v[2]:v[0]+v[1]+v[2]+v[3]])`


I'm thinking about make this clearer, but closest one I have so far is (note the results are incorrect, not what I wanted)

s=0
[list1,list2,list3,list4] = [l[s:s+i] for i in v]


the problem is I couldn't increase
s
at the same time while iterating values in
v
, I'm hoping to get a better code to do so, any suggestion is appreciated, thanks!

Answer

Maybe make a generator of the values in l?

def make_list(l, v):
    g = (x for x in l)
    if len(l) == sum(v):
       return [[next(g) for _ in range(val)] for val in v]
    return None