0

I have a list l = ['AAB', 'CAA', 'ADA'] . I want to get the following list without duplicated characters new_l = ['AB','CA','AD']. I am trying to iterate on a nested loop but I'm not sure this is the best way to accomplish this. here is my try:

new_l = []

for i in range(0,len(l)-1):
    for j in range(0,len(l)-1):
        if l[i][j] != l[i+1][j+1]:
            new_l = ..............

Can someone help me on how to get a set by iterating over every element of this list of strings ?

Logica
  • 977
  • 4
  • 16
moth
  • 1,833
  • 12
  • 29

3 Answers3

2

You can easily do it, since a string is also a list.

strl = ['AAB', 'CAA', 'ADA']
new_strl = []
for s in strl:
  new_strl.append("".join(set(s)))

print(new_strl)
venkata krishnan
  • 1,961
  • 1
  • 13
  • 20
1

Set can mess order of characters. Better use OrderedDict:

from collections import OrderedDict
strl = ['AAB', 'CAA', 'ADA']
result = ["".join(OrderedDict.fromkeys(s)) for s in strl]
Raymond Reddington
  • 1,709
  • 1
  • 13
  • 21
  • 1
    Note: In python3.7 or above the order of the keys is preserved in dictionaries. – Ch3steR Mar 16 '20 at 05:32
  • @Zaven Zareyan could you explain your code since `.fromkeys` Create a new ordered dictionary with keys from iterable and values set to value. I don't get how `.fromkeys` make a `set` of `strl` – moth Mar 16 '20 at 07:00
  • You're joining by `""` character (i.e. by nothing) the keys of OrderedDict (`join` method goes only to keys) created from keys, (i.e. `{'key1': None, 'key2': None}`). – Raymond Reddington Mar 16 '20 at 07:07
  • sorry still don't understand why joining by empty character will remove duplicates – moth Mar 16 '20 at 07:47
  • 1
    OrderedDict makes your string like: `'AAB'-> {'A': None, 'B': None}` and removes duplicates. Then you're joining keys and get 'AB' – Raymond Reddington Mar 16 '20 at 07:52
  • ok now I understood thanks. I tried the normal `dictionary` and it also works since the order is preserved in python 3.7 or above. – moth Mar 16 '20 at 08:04
1
l = ['AAB', 'CAA', 'ADA']
new_l = [''.join(sorted(set(x))) for x in l]
#op
['AB', 'AC', 'AD']
qaiser
  • 2,770
  • 2
  • 17
  • 29