Cranjis
Cranjis

Reputation: 1960

python list convert to list with unique on subsequences

I have a list that looks like this:

["A","A","A","A", "B","B","B","A","A","C","C,"B","B","A"]

A I want to run unique on all sub-sequences , so the output will be:

["A","B","A","C","B","A"]

What is the best way to do so?

Thanks

Upvotes: 1

Views: 56

Answers (3)

RoadRunner
RoadRunner

Reputation: 26315

Use itertools.groupby inside a list comprehension:

>>> from itertools import groupby
>>> lst = ["A","A","A","A","B","B","B","A","A","C","C","B","B","A"]
>>> [k for k, _ in groupby(lst)]
['A', 'B', 'A', 'C', 'B', 'A']

Another functional approach using map and operator.itemgetter:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> lst = ["A","A","A","A","B","B","B","A","A","C","C","B","B","A"]
>>> list(map(itemgetter(0), groupby(lst)))
['A', 'B', 'A', 'C', 'B', 'A']

Upvotes: 2

gstukelj
gstukelj

Reputation: 2551

If you want a convoluted one-liner, you can do it with a list comprehension:

>>> l = ["a", "b", "a", "a", "x", "x", "a", "a", "a"]
>>> x = [l[x] for x in range(len(l)) if x == 0 or l[x - 1] != l[x]]
['a', 'b', 'a', 'x', 'a']

Here's another idea using reduce from functools. I think it's an overkill, but maybe it can help you work it into something better:

>>> from functools import reduce
>>> r = lambda x,y: x+y if x[-1] != y else x  ## reduce function
>>> reduce(r, l)  ## you could write in lambda directly
'abaxa'
>>> list(reduce(r,l))
['a', 'b', 'a', 'x', 'a']

Upvotes: 2

oliverm
oliverm

Reputation: 123

Assuming your sublists are sorted as in the question you could do something like:

unique_list = []
unique_list.append(your_list[0])
for literal in your_list
    if not unique_list[-1] is literal
        unique_list.append(literal)

However, this will not be a very fast solution an there are probably better ways to do it.

Upvotes: 0

Related Questions