首页 > 解决方案 > 计数字符串出现次数/枚举列表中的出现次数

问题描述

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

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

标签: python

解决方案


test = int(input())
l=[]

for i in range(test):
  l.append(input())
res=[]
for i in range(len(l)):
   count =l[:i].count(l[i])
   if count==0:
      res.append(l[i])
   else:
      res.append(l[i]+str(count))
print(res)

推荐阅读