如何从具有重复项的列表中创建唯一列表

How to create unique list from list with duplicates

我知道如何使用 set() 或两个列表从列表中删除重复项,但如何维护同一个列表并在末尾添加一个数字来表示重复项?我可以用 if 来做,但它不是 pythonic。谢谢大家!!

nome_a = ['Anthony','Rudolph', 'Chuck', 'Chuck', 'Chuck', 'Rudolph', 'Bob']
nomes = []

for item in nome_a:  
    if item in nomes:

        if (str(item) + ' 5') in nomes:
            novoitem = str(item) + ' 6'
            nomes.append(novoitem)

        if (str(item) + ' 4') in nomes:
            novoitem = str(item) + ' 5'
            nomes.append(novoitem)

        if (str(item) + ' 3') in nomes:
            novoitem = str(item) + ' 4'
            nomes.append(novoitem)

        if (str(item) + ' 2') in nomes:
            novoitem = str(item) + ' 3'
            nomes.append(novoitem)

        else:
            novoitem = str(item) + ' 2'
            nomes.append(novoitem)

    if item not in nomes:
        nomes.append(item)

print(nomes)

编辑(1):抱歉。我编辑澄清。

您可以使用以下内容:

names = ['Anthony','Rudolph', 'Chuck', 'Chuck', 'Chuck', 'Rudolph', 'Bob']

answer = []
name_dict = {}

for name in names:
    if name_dict.get(name):
        name_dict[name] += 1
        answer.append('{}_{}'.format(name, name_dict[name]))
    else:
        name_dict[name] = 1
        answer.append(name)

print(answer)

输出

['Anthony', 'Rudolph', 'Chuck', 'Chuck_2', 'Chuck_3', 'Rudolph_2', 'Bob']