开发者

How to remove duplicates in strings within list? [closed]

开发者 https://www.devze.com 2023-04-12 11:52 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its c开发者_高级运维urrent form.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its c开发者_高级运维urrent form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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:

  1. Create a dictionary for each key wordN
  2. In this key, convert item 2 through n of list to a set
  3. 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']
0

精彩评论

暂无评论...
验证码 换一张
取 消