python - 计数字符串出现次数/枚举列表中的出现次数
问题描述
我需要更新列表,如下所示
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']
解决方案
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)
推荐阅读
- java - 你如何比较 Java 中的时间?
- python - 如何让程序在后台监听键盘事件?
- javascript - 如何根据元素位置调用函数?
- django - 使用 Django SQL Explorer 如何正确设置具有 PostgreSQL 后端的参数的默认日期?
- ruby-on-rails - 在视图中使用foreach时如何在控制器中获取表单参数
- python - 恢复上次训练的训练变量
- pine-script - 在当前时间帧上绘制另一个时间帧的指标
- raft - raft算法leader选举有终止保证吗?
- php - 未定义的变量,尽管它在页脚部分 TCPPDF 中定义
- mpi - 在哪里初始化数组然后分散它。MPI_Scatter