Split list after repeating elements
I have this loop to create 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 will N = [2, 3, 4]
provide a 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 to create separate lists after each 1.0 item. 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 about using an if test like
for c_ in c:
if c_ == 1.0:
anotherList.append(c_)
This only adds 1.0, and I don't know how I can do it by adding just one after one, not just 1.0.
+3
source to share
2 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]]
+5
source to share