【发布时间】:2021-09-10 14:05:25
【问题描述】:
有一个列表包含“托尔金”书籍,另一个包含“指环王”书籍。
《指环王》中的一些书与《托尔金》中的书相同。
我想使用 for 循环来检查“托尔金”书籍中的哪些书籍与“指环王”书籍中的书籍相同。如果 for 循环找到匹配项,它会将 Tolkien 列表中的项目更改为“LOTR book: {Tolkien book}”
我的问题是: for 循环改变了托尔金列表中的项目。 我知道它会重新匹配匹配项,但它不会更改列表。 这是为什么呢?
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"]
for T_book in Tolkien_books:
for LOTR_book in Lord_Of_The_Rings:
if LOTR_book == T_book:
T_book = f"LOTR: {T_book}"
print(Tolkien_books)
【问题讨论】:
-
T_book =不会更改T_book所引用的对象,它会更改T_book以引用不同的对象。
标签: python list loops for-loop