Bill Chung - 9 months ago 53

Python Question

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`

`v`

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
```

Source (Stackoverflow)