首页 > 解决方案 > 删除字符串中第一次出现的单词

问题描述

test = 'User Key Account Department Account Start Date'

我想从字符串中删除重复的单词。这个问题的解决方案运作良好......

def unique_list(l):
     ulist = []
     [ulist.append(x) for x in l if x not in ulist]
     return ulist

test = ' '.join(unique_list(test.split()))

但它只保留后续的副本。我想删除字符串中的第一个匹配项,以便测试字符串显示为“用户密钥部门帐户开始日期”。

标签: pythonduplicates

解决方案


这应该做的工作:

test = 'User Key Account Department Account Start Date'

words = test.split()

# if word doesn't exist in the rest of the word list, add it
test = ' '.join([word for i, word in enumerate(words) if word not in words[i+1:]])

print(test)  # User Key Department Account Start Date

推荐阅读