python - 根据值是否已存在于列表中追加
问题描述
我有一个空列表。我想在其中附加字符串,但如果它们已经存在,可以稍微改变一下。像这样的东西:
姓名:约翰、大卫、约翰、路易斯、肖恩、约翰、大卫
附加后的列表:John, David, John_2, Luis, Sean, John_3, David_2
我在想这样的事情:
names_list = []
names = [ 'John' , 'David', 'John', 'Luis, 'Sean', 'John', 'David']
itter = 1
for _ in names:
if any(names[_] in s for s in name_list):
button_list.append(names[_] + f'_{itter+1}')
itter+=1
else:
button_list.append(names[_])
然而,这给了我们:约翰,大卫,约翰_2,路易斯,肖恩,约翰_3,大卫_4(最后一个大卫需要是大卫_2)。我找不到根据特定名称的出现次数更改itter的方法。提前感谢您的帮助。
解决方案
你可以有generator
这样的:
In [3215]: def rename_duplicates(old):
...: seen = {}
...: for x in old:
...: if x in seen:
...: seen[x] += 1
...: yield "%s_%d" % (x, seen[x])
...: else:
...: seen[x] = 1
...: yield x
...:
In [3216]: list(rename_duplicates(names))
Out[3216]: ['John', 'David', 'John_2', 'Luis', 'Sean', 'John_3', 'David_2']
推荐阅读
- c# - 从 odata RawValues 中提取字符串列表
- java - status":500,"error":"内部服务器错误(Spring Boot 和 cURL)
- docker - 重复传输大镜像到docker容器注册中心的问题
- angular - 从 Angular 对话框模板提交表单
- javascript - 如何通过外部命令停止异步处理的执行
- c++ - 如何为具有共享指针的结构的多索引制作修饰符以提升记录器后端以重置此后端?
- python - 如何检查表中不存在用户名?
- javascript - 从 HTML“onclick”运行外部 Javascript 函数
- java - 为什么 Spring 框架不记录 Autowired Setter 注入?
- bash - 解析逗号分隔的字符串并将其保存到 bash 中的文件中