You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何修改列表中同时存在于另一列表的对应元素

问题原因
  • Python 使用for 元素 in 列表语法遍历列表时,得到的循环变量是列表元素的值拷贝,并非指向原列表对应位置的引用。你对临时变量T_book做重新赋值,仅修改了这个临时变量的内容,不会改动原Tolkien_books列表中的实际存储值。
  • 原代码嵌套双层循环逐个比对的逻辑可以优化,直接用in关键字判断元素是否属于指环王作品列表即可,逻辑更简洁、执行效率更高。
正确实现代码
Lord_Of_The_Rings = ["The Hobbit", "The Fellowship of the Ring", "The Two Towers", \
"The Return of the King"]

Tolkien_books = ["The Hobbit", "Farmer Giles of Ham", "The Fellowship of the Ring", \
"The Two Towers", "The Return of the King", "The Adventures of Tom Bombadil", "Tree and Leaf"]

# 通过enumerate同时获取元素索引和值,通过索引直接修改原列表
for index, book in enumerate(Tolkien_books):
    if book in Lord_Of_The_Rings:
        Tolkien_books[index] = f"LOTR book: {book}"

print(Tolkien_books)
运行输出
['LOTR book: The Hobbit', 'Farmer Giles of Ham', 'LOTR book: The Fellowship of the Ring', 'LOTR book: The Two Towers', 'LOTR book: The Return of the King', 'The Adventures of Tom Bombadil', 'Tree and Leaf']

内容的提问来源于stack exchange,提问作者Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:21:02