Not sure how else to word this, but say I have a list containing the following sequence:
[a,a,a,b,b,b,a,a,a]
and I would like to return:
[a,b,a]
How would one do this in principle?
Not sure how else to word this, but say I have a list containing the following sequence:
[a,a,a,b,b,b,a,a,a]
and I would like to return:
[a,b,a]
How would one do this in principle?
You can use
itertools.groupby
, this groups consecutive same elements in the same group and return an iterator of key value pairs where the key is the unique element you are looking for:Psidoms way is a lot better, but I may as well write this so you can see how it'd be possible just using basic loops and statements. It's always good to figure out what steps you'd need to take for any problem, as it usually makes coding the simple things a bit easier :)
Basically it will append a letter if the previous letter is something different.
Using list comprehension:
Similarly (thanks to pylang) you can use
enumerate
instead ofrange
:more_itertools
has an implementation of theunique_justseen
recipe fromitertools
: