I have a list of integers, in which some are consecutive numbers.
What I have:
myIntList = [21,22,23,24,0,1,2,3,0,1,2,3,4,5,6,7]
etc...
What I want:
MyNewIntList = [[21,22,23,24],[0,1,2,3],[0,1,2,3,4,5,6,7]]
I want to be able to split this list by the element 0, i.e when looping, if the element is 0, to split the list into separate lists.
Then, after splitting myIntList
whatever number of times (based on the recurrences of finding the element 0), I want to append each 'split' or group of consecutive integers into a list within a list.
Also would I be able to do the same sort of thing with a 'list of strings' instead of integers? (Split the main string list into smaller lists based on a reoccurring element)
EDIT:
How would I go about splitting the list by consecutive numbers? There's a part in my list where it jumps from 322 to 51, there is no 0 in between. I want to split:
[[...319,320,321,322,51,52,53...]]
into
[[...319,320,321,322],[51,52,53...]]
basically, how do I split elements in a list by consecutive numbers?
Posted here: Split list of lists (integers) by consecutive order into separate lists
it = iter(myIntList)
out = [[next(it)]]
for ele in it:
if ele != 0:
out[-1].append(ele)
else:
out.append([ele])
print(out)
Or in a function:
def split_at(i, l):
it = iter(l)
out = [next(it)]
for ele in it:
if ele != i:
out.append(ele)
else:
yield out
out = [ele]
yield out
It will catch if you have a 0
at the start:
In [89]: list(split_at(0, myIntList))
Out[89]: [[21, 22, 23, 24], [0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 6, 7]]
In [90]: myIntList = [0,21, 22, 23, 24, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7]
In [91]: list(split_at(0, myIntList))
Out[91]: [[0, 21, 22, 23, 24], [0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 6, 7]]
(I vaguely suspect I've done this before but I can't find it now.)
from itertools import groupby, accumulate
def itergroup(seq, val):
it = iter(seq)
grouped = groupby(accumulate(x==val for x in seq))
return [[next(it) for c in g] for k,g in grouped]
gives
>>> itergroup([21,22,23,24,0,1,2,3,0,1,2,3,4,5,6,7], 0)
[[21, 22, 23, 24], [0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 6, 7]]
>>> itergroup([0,1,2,0,3,4], 0)
[[0, 1, 2], [0, 3, 4]]
>>> itergroup([0,0], 0)
[[0], [0]]
(That said, in practice I use the yield
version of the same loop/branch that everyone else does, but I'll post the above for variety.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With