Is there a way to use list comprehensions in python to filter adjacent duplicates from a list?
Here's an example of what I mean:
>>> xs = [1,2,2,3]
>>> print added.reAdj(xs)
[1,2,3]
A search through SE revealed an earlier inquiry asking a similar but slightly different question: whether all duplicates could be removed from a list, but not explicitly asking for solutions involving list comprehensions. The motivation for using list comprehensions specifically follows a recognition of their advantages over traditional for loops. Users suggested the use of the set() function or standard looping as such:
result = []
most_recent_elem = None
for e in xs:
if e != most_recent_elem:
result.append(e)
most_recent_elem = e
The set()
suggestion fails to meet the task in that non-adjacent duplicates are removed, while the loop is effective but verbose.
It seems a means for safely referencing the next element in a list comprehension as follows is needed.
[x for x in xs if x != **x.next()**]
Any ideas?