2

I've the following array with multiple repetitions and I want to remove them mantaining the order.

v = ['maier', 'tapa pure', 'embega', 'maier', 'tapa pure', 'embega', 'maier', 'tapa pure', 'embega', 'maier', 'tapa pure', 'embega', 'maier', 'tapa pure', 'embega', 'maier', 'tapa pure', 'embega', 'maier', 'tapa pure', 'embega', 'maier', 'tapa pure', 'embega']

I use list(set(v)) and I get the following output:
['embega', 'maier', 'tapa pure']

What I want to have is to remove the repetition, but maintain the original order:
['maier', 'tapa pure', 'embega']

I cant use v[:3] because the repetitions length is variable.

How can I do it?

Thanks in advance.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Avión
  • 7,963
  • 11
  • 64
  • 105

2 Answers2

5

You should be using collections.OrderedDict's fromkeys function, like this

from collections import OrderedDict
print OrderedDict.fromkeys(v).keys()
# ['maier', 'tapa pure', 'embega']
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3
seen_items = set()
w = [] 
for item in v:
    if item not in seen_items:
        w.append(item)
        seen_items.add(item)
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52