gpt4 book ai didi

python - 计算字符串出现次数/枚举列表中的出现次数

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:40 25 4
gpt4 key购买 nike

我需要更新列表,如下所示

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

关于python - 计算字符串出现次数/枚举列表中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58530678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com