如果我有这个清单:
['hello world', 'latest.png', 'have a good day', 'stack overflow', 'the best'
'latest .png', 'i believe somebody will help me', 'latest.png', 'latest.png']
是否可以将第一个
latest.png
更改为latest1.png
,将下一个latest.png
更改为latest2.png
等?
有什么优雅的方法吗?非常感谢
@Barmar 的评论很好地解释了这一点。
假设
words
是您的列表,您的代码将如下所示:
latest_count = 1
new_words = []
for word in words:
if word == "latest.png":
new_words.append(f"latest{latest_count}.png")
latest_count += 1
else:
new_words.append(word)
new_words
将包含您更新的列表,并且您仍然拥有原始列表。