如何在Python列表中对指定字符串进行递增序号替换?
解决方案
可以通过计数器配合遍历的方式实现,核心是精准匹配latest.png字符串(注意区分带空格的latest .png,该元素不做替换),按出现顺序递增编号:
基础实现代码
original_list = ['hello world', 'latest.png', 'have a good day', 'stack overflow', 'the best', 'latest .png', 'i believe somebody will help me', 'latest.png', 'latest.png'] count = 0 result = [] for item in original_list: if item == 'latest.png': count += 1 result.append(f'latest{count}.png') else: result.append(item) print(result)
代码说明
- 初始化计数器
count为0,遍历原列表每个元素 - 当元素完全等于
latest.png时,计数器自增,替换为带编号的新字符串 - 其他元素(包括带空格的
latest .png)直接保留原内容加入结果列表
运行结果
输出的结果列表为:
['hello world', 'latest1.png', 'have a good day', 'stack overflow', 'the best', 'latest .png', 'i believe somebody will help me', 'latest2.png', 'latest3.png']
更简洁的写法
可以借助itertools.count自动生成递增序号,用列表推导式压缩代码:
from itertools import count original_list = ['hello world', 'latest.png', 'have a good day', 'stack overflow', 'the best', 'latest .png', 'i believe somebody will help me', 'latest.png', 'latest.png'] cnt = count(1) result = [f'latest{next(cnt)}.png' if item == 'latest.png' else item for item in original_list]
内容的提问来源于stack exchange,提问作者Max Sikorsky
相关产品推荐
相关产品推荐

