Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list after repeating elements

Tags:

python

list

I have this loop for creating a list of coefficients:

for i in N:
    p = 0
    for k in range(i+1):
        p += (x**k)/factorial(k)
        c.append(p)

For example N = [2, 3, 4] would give list c:

[1.0, 2.0, 2.5, 1.0, 2.0, 2.5, 2.6666666666666665, 1.0, 2.0, 2.5, 2.6666666666666665, 2.708333333333333]

I want a way of making separate lists after each 1.0 element. For example a nested list:

[[1.0, 2.0, 2.5], [1.0, 2.0, 2.5, 2.6666666666666665], [1.0, 2.0, 2.5, 2.6666666666666665, 2.708333333333333]]

I was thinking of using an if test, like

for c_ in c:
    if c_ == 1.0:
        anotherList.append(c_)

This only appends 1.0's though and I don't know how I can make it append everything after a one instead of just 1.0.

like image 876
AndreyATGB Avatar asked Feb 11 '26 21:02

AndreyATGB


1 Answers

you can use itertools.groupby in list comprehension :

>>> [[1.0]+list(g) for k,g in itertools.groupby(l,lambda x:x==1.0) if not k]
[[1.0, 2.0, 2.5], [1.0, 2.0, 2.5, 2.6666666666666665], [1.0, 2.0, 2.5, 2.6666666666666665, 2.708333333333333]]
like image 128
Mazdak Avatar answered Feb 13 '26 12:02

Mazdak