在 python 中使用 for 循环为迭代器的元素分配新值时出现问题

Trouble with assigning new values to the elements of an iterator using for loop in python

我在使用 for 循环为迭代器的元素分配新值时遇到问题。假设我们有这个列表:

some_2d_list = [['mean', 'really', 'is', 'jean'],
 ['world', 'my', 'rocks', 'python']]
为什么此代码有效并更改原始列表的元素(反转本身是列表的元素):

for items in some_2d_list:
        items = items.reverse()

但是这个没有(在这种情况下我们将不得不使用索引来应用更改):

for items in some_2d_list:
        items = ["some new list"]
我期待后一个代码的结果:

some_2d_list = [["some new list"],
 ["some new list"]]

list.reverse原地反转,returnsNone,所以

for items in some_2d_list:
    items = items.reverse()

反转仍在some_2d_list中的现有列表并将None分配给items

当您在for items in some_2d_list中输入代码块时,items是对仍在some_2d_list中的对象的引用。任何修改现有列表的内容也会影响 some_2d_list。例如

>>> some_2d_list = [['mean', 'really', 'is', 'jean'],
...  ['world', 'my', 'rocks', 'python']]
>>> 
>>> for items in some_2d_list:
...     items.append('foo')
...     del items[1]
... 
>>> some_2d_list
[['mean', 'is', 'jean', 'foo'], ['world', 'rocks', 'python', 'foo']]

像“+=”这样的增强操作是不明确的。根据任何给定类型的实现方式,它可以就地更新或创建新对象。他们为列表工作

>>> some_2d_list = [['mean', 'really', 'is', 'jean'],
...  ['world', 'my', 'rocks', 'python']]
>>> 
>>> for items in some_2d_list:
...     items += ['bar']
... 
>>> some_2d_list
[['mean', 'really', 'is', 'jean', 'bar'], ['world', 'my', 'rocks', 'python', 'bar']]

但不适用于元组

>>> some_2d_list = [('mean', 'really', 'is', 'jean'), ('world', 'my', 'rocks', 'python')]
>>> for items in some_2d_list:
...     items += ('baz',)
... 
>>> some_2d_list
[('mean', 'really', 'is', 'jean'), ('world', 'my', 'rocks', 'python')]