gpt4 book ai didi

python - 删除字符串中第一次出现的单词

转载 作者:行者123 更新时间:2023-12-02 02:05:46 26 4
gpt4 key购买 nike

test = '用户关键帐户部门帐户开始日期'

我想从字符串中删除重复的单词。来自this question的解决方案功能良好...

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()))

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

最佳答案

这应该可以完成工作:

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

关于python - 删除字符串中第一次出现的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68475659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com