How to remove duplicates in strings within list? [closed]
I have list of string but in each string is duplicate I need to remove. f.e.:
lst = ('word1 2 36 2 2' ' word2 96 5 5 5 14' 'word3 45 6 45 45')
etc.
I need:
lst = ('word1 2 36' 'word2 96 5 14' 'word3 45 6')
Generally:
- Create a
dictionary
for each key wordN - In this key, convert item 2 through n of
list
to aset
- Iterate through the dictionary, building a new list from each key and its set's contents
Your question is not very clear, and as-written your "list" isn't a list but a string. I guess you probably meant to make it a tuple, but even then you need commas between the items.
In the following example, we iterate over the items, split the string split() function, add the items to a set, join them together again with the string join, and append them to our output list (a real list this time):
>>> lst = ('word1 2 36 2 2', ' word2 96 5 5 5 14', 'word3 45 6 45 45')
>>> out = []
>>> for item in lst:
... tokens = item.split()
... s = set(tokens)
... joined = " ".join(s)
... out.append(joined)
...
>>> out
['2 word1 36', '96 5 14 word2', '45 word3 6']
This can be written more compactly with a list comprehension:
>>> lst = ('word1 2 36 2 2', ' word2 96 5 5 5 14', 'word3 45 6 45 45')
>>> out = [" ".join(set(item.split())) for item in lst]
>>> out
['2 word1 36', '96 5 14 word2', '45 word3 6']
精彩评论