如何将Python列表中的一个单词替换为另一个单词

问题描述 投票:0回答:1

如果我有这个清单:

['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
等?

有什么优雅的方法吗?非常感谢

python list replace
1个回答
0
投票

@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
将包含您更新的列表,并且您仍然拥有原始列表。

© www.soinside.com 2019 - 2024. All rights reserved.