python - 如何重命名列表项以使它们都是唯一的?

标签 python list

我有一个这样的列表:

lista=['a','b','b','c','d','e','c','e','b','b']

请注意,该列表将从其他来源填写,所以我不知道项目和编号

我需要的是这个结果:

['a','b','b_1','c','d','e','c_1','e_1','b_2','b_3']

我尝试了递归检查,但它不能保证检测到所有重复... 提前致谢!!

最佳答案

您可以创建一个计数器变量来跟踪已看到的数量:

lista = ['a','b','b','c','d','e','c','e','b','b']

output = []
counter = {}

for x in lista:
    if x in counter.keys():
        output.append(f"{x}_{counter[x]}")
        counter[x] += 1
    else:
        output.append(x)
        counter[x] = 1

print(output) # ['a', 'b', 'b_1', 'c', 'd', 'e', 'c_1', 'e_1', 'b_2', 'b_3']

或者,使用 collections.Counter:

from collections import Counter

lista = ['a','b','b','c','d','e','c','e','b','b']

output = []
counter = Counter()
for x in lista:
    output.append(f"{x}_{counter[x]}" if counter[x] else x)
    counter.update(x)

关于python - 如何重命名列表项以使它们都是唯一的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74266797/

相关文章:

python - 使用 notify-send 的 python 脚本的 crontab

python - QGraphicsScene 鼠标事件

python - 如何将列名从元组更改为字符串?

python - 使用 python 从 XML 中的子项中查找父项

python - 当在 pandas DataFrame 上使用 apply 时,获取列表是不可散列的

python - 替换列表中的无值?

list - 在 R 中将向量设置为列表组件

r - 从列表创建数据框

list - 附加列表以显示在 Racket 的文本字段中

list - 右对齐后伪