首页 > 解决方案 > 根据值是否已存在于列表中追加

问题描述

我有一个空列表。我想在其中附加字符串,但如果它们已经存在,可以稍微改变一下。像这样的东西:

姓名:约翰、大卫、约翰、路易斯、肖恩、约翰、大卫

附加后的列表: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的方法。提前感谢您的帮助。

标签: pythonpython-3.xlist

解决方案


你可以有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']

推荐阅读