python - 删除字符串中第一次出现的单词
问题描述
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()))
但它只保留后续的副本。我想删除字符串中的第一个匹配项,以便测试字符串显示为“用户密钥部门帐户开始日期”。
解决方案
这应该做的工作:
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
推荐阅读
- scala - 在运行时在 spark-scala shell 中获取 spark conf 值
- android - Android Kotlin recycler view in the fragment is not loaded with the right data when set up with TabLayout/ ViewPager sharing same fragment class
- ruby-on-rails - 我应该在哪里放置逻辑在 Ruby on Rails 项目中
- multidimensional-array - Convert 2D array to list of lists
- docker - Docker Desktop for mac OS 中的暴露和映射端口有时会在主机上返回空回复
- javascript - 如何使用 javascript 函数在 cypress 中关闭打开的打印窗口
- c# - NT AUTHORITY\Local 服务未列在目录的访问控制列表中
- cmake - 为静态库用户提供源文件夹外的包含目录
- c# - 有没有办法找到未等待的任务?
- sql - 使用 SQL Developer 连接到 Oracle 12C 数据库服务器 (12.2.0)