Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python列表中重命名重复项_Python_Python 3.x_List - Fatal编程技术网

在python列表中重命名重复项

在python列表中重命名重复项,python,python-3.x,list,Python,Python 3.x,List,我有一张名单,像这样 names =['Jack','Jerry',Jerry','Jerry','Jerry','Jerry','Phillips','Phillips','Phillips','Phillips','Harry','Harry','Harry','Harry','Harry'.....] 我想重命名重复项,因为结果列表应该是 names = ['Jack','Jerry',Jerry_2','Jerry_3','Jerry_4','Jerry_5','Phillips','

我有一张名单,像这样

names =['Jack','Jerry',Jerry','Jerry','Jerry','Jerry','Phillips','Phillips','Phillips','Phillips','Harry','Harry','Harry','Harry','Harry'.....]
我想重命名重复项,因为结果列表应该是

names = ['Jack','Jerry',Jerry_2','Jerry_3','Jerry_4','Jerry_5','Phillips','Phillips_2','Phillips_3','Phillips_4','Harry','Harry_2','Harry_3','Harry_4','Harry_5'.....]

我尝试过代码,但我的逻辑不太好,有人能帮我吗?

保留一本字典,列出你遇到的所有不同名称,并记下你遇到它们的次数:

def rename_重复项(名称):
seen=dict()
对于i,枚举中的名称(名称):
如果名称不在列表中:
seencount[名称]=1
其他:
已看到[name]+=1
名称[i]+=f'{seen[name]}
返回名称

只需保留一本计数字典:

In [12]: names = ['Jack','Jerry', 'Jerry','Jerry','Jerry','Jerry','Phillips','Phillips','Phillips','Phillips','Harry','Harry','Harry','Harry','Harry']
    ...:
    ...:

In [13]: counts = {}

In [14]: for i, name in enumerate(names):
    ...:     if name in counts:
    ...:         counts[name] += 1
    ...:         names[i] = f"{name}_{counts[name]}"
    ...:     else:
    ...:         counts[name] = 1
    ...:

In [15]: names
Out[15]:
['Jack',
 'Jerry',
 'Jerry_2',
 'Jerry_3',
 'Jerry_4',
 'Jerry_5',
 'Phillips',
 'Phillips_2',
 'Phillips_3',
 'Phillips_4',
 'Harry',
 'Harry_2',
 'Harry_3',
 'Harry_4',
 'Harry_5']

让我们保留一个计数器对象来帮助我们:

从集合导入计数器
def更新_重复(lst)->列表:
名称\计数器=计数器()
对于范围内的i(len(lst)):
名称#计数器。更新([lst[i]])#更新我们的计数器
如果name_counter[lst[i]]>1:#重复,让我们更新列表值
lst[i]=lst[i]+f'{name_counter[lst[i]}'
返回lst

将它们重命名为什么?