如何从重复列表中创建唯一列表

2024-04-26 07:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何使用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):对不起。为了澄清我编辑了。你知道吗


Tags: in编辑列表if数字item末尾set
1条回答
网友
1楼 · 发布于 2024-04-26 07:26:25

您可以使用以下选项:

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']

相关问题 更多 >