我需要更新列表,如下所示
l=['hey','alan','hey','hey','hey','alan']
结果必须是
l=['hey','alan','hey1','hey2','hey3','alan1']
我的代码:
test = int(input())
texts=[]
for i in range(test):
texts.append(input())
res=[]
for i in texts:
if i in res:
# print(i)
c=res.count(i)
o=i+str(c)
res.append(o)
else:
res.append(i)
print(res)
实际输出:
['hey', 'hey1', 'hey1']
预期输出:
['hey', 'hey1', 'hey2']
您可以使用字典来记录出现次数:
l = ['hey', 'alan', 'hey', 'hey', 'hey', 'alan']
d = {}
result = []
for key in l:
result.append(f'{key}{d[key]}' if key in d else key)
if key not in d:
d[key] = 0
d[key] += 1
print(result)
输出
['hey', 'alan', 'hey1', 'hey2', 'hey3', 'alan1']
我是一名优秀的程序员,十分优秀!