Removing duplicates from individual strings in a list

LeoHurab :

I'm attempting to write a python program that if given a list of strings, will remove duplicate characters from the individual strings of the list. My work so far is:

#program: removeduplicates.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-lst", nargs='+', type=str, required=True)
xyz = parser.parse_args()
duplist = xyz.lst

def duplicate_destoryer(duplist):
    finallist = []
    for word in duplist:
        x = set()
        list = []
        for ch in word:
            if ch not in x:
                set.add(ch)
                list.append(ch)
        finallist.append(list)

    return finallist


if __name__ == "__main__":
    print(duplicate_destoryer(duplist))

In my command line I input

python removeduplicates.py -lst aarrtt ddwwtt

and my desired output is(doesn't matter if in list brackets or simply written out):

art dwt

The code I wrote makes sense to me logically, but I keep getting the error descriptor 'add' for 'set' objects doesn't apply to a 'str' object That is fair and all but as I do further research I feel like I keep coming across more and more examples of code where set.add() is being used with string objects.

Could someone point me in the right direction or tell me what I'm doing wrong here?

Austin :

You are very very close. Just need to use following:

x.add(ch)

instead of:

set.add(ch)

That would fetch a list of lists as output as opposed to a list of strings you would expect. To correct that you can do:

finallist.append(''.join(list))

instead of:

finallist.append(list)

Note that you should not be using list for variable name. It's is a Python built-in.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390804&siteId=1