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
相关产品推荐
相关产品推荐

