How to get unique values from list in specific order?

Viewed 88

I have a list with repeated values like below:

L1 = ['r-A','r-G','S1','r-A','S2','r-O','r-G','S2','S1','r-A']

And like to remove repeated elements containing 'r-' leaving the first value only in the corresponding position.

This is:

For 'r-A' select L1[0] and in output would be L2[0]
For 'r-G' select L1[1] and in output would be L2[1]
For 'r-O' select L1[5] and in output would be L2[4]

So the output list would be:

L2 = ['r-A','r-G','S1','S2','r-O','S2','S1']

Using set() I get the unique values but it shows them in different order and removes values that don´t contain r-

>>> list(set(L1))
['S2', 'S1', 'r-A', 'r-G', 'r-O']

How can I do this?

5 Answers
final = []
[final.append(x) for x in L1 if not x in final or not "r-" in x]

You can do it with simple for loop, first check string startwith r- then check if it is already in output list else add it

L1 = ['r-A','r-G','S1','r-A','S2','r-O','r-G','S2','S1','r-A']
result = list()

for i in L1:
    if i.startswith('r-'):
        if i not in result:
            result.append(i)
    else:
      result.append(i)

print(result) # ['r-A', 'r-G', 'S1', 'S2', 'r-O', 'S2', 'S1']

This should do it:

L1 = ['r-A','r-G','S1','r-A','S2','r-O','r-G','S2','S1','r-A']
L2 = []
for item in L1:
    if 'r-' in item and item  in L2:
         continue
    else:
        L2.append(item)
print(L2)

Output:

['r-A', 'r-G', 'S1', 'S2', 'r-O', 'S2', 'S1']

This should work as well:

 L1 = ['r-A','r-G','S1','r-A','S2','r-O','r-G','S2','S1','r-A']

 newL1 = []
 for element in L1:
    if element == "S1":
      newL1.append(element)
    elif element == "S2":
      newL1.append(element)
    else:
      if element not in newL1:
        newL1.append(element)
 print(newL1)

Output:

>>>['r-A', 'r-G', 'S1', 'S2', 'r-O', 'S2', 'S1']

Short one with O(n) time.

>>> d = dict.fromkeys(L1, 1)
>>> [x for x in L1 if x[:2] != 'r-' or d.pop(x, 0)]
['r-A', 'r-G', 'S1', 'S2', 'r-O', 'S2', 'S1']

I'm keeping track of the r--elements I can still use instead of the ones I have already used. It's a little easier because dict.pop can be used in an expression and both removes and returns a value.

Related