3 回答
TA贡献1801条经验 获得超16个赞
这可能不是最有效的方法。
ls = ["a", "a", "b", "b", "b", "b", "c"]
UniqueValues = set(ls)
for x in UniqueValues:
number = 0
for i in range(0,len(ls)):
if ls[i] == x:
number += 1
if number >= 2:
ls[i] += str(number)
但我们得到你要找的东西
print(ls)
['a', 'a2', 'b', 'b2', 'b3', 'b4', 'c']
TA贡献1851条经验 获得超4个赞
你可以使用Counter和unique方法。
from numpy import unique
from collections import Counter
ls = ["a", "a", "b", "b", "b", "b", "c"]
dup = dict(Counter(ls))
l_uniq = unique(ls)
print([key if i == 0 else key + str(i+1) for key in l_uniq for i in range(dup[key])])
出去:
['a', 'a2', 'b', 'b2', 'b3', 'b4', 'c']
TA贡献1998条经验 获得超6个赞
所以我们每次都需要检查完整列表,以便如果存在相同的值,我们可以更改指向值。
ls = ["a", "a", "b", "b", "b", "b", "c",'a','a']
for index,value in enumerate(ls):
if value in ls[index+1:]:
for new in range(0,200000000):
if not f'{value}{new}' in ls:
ls[index] = f'{value}{new}'
break
print(ls)
输出:
['a0', 'a1', 'b0', 'b1', 'b2', 'b', 'c', 'a2', 'a']
添加回答
举报