Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用for循环为迭代器的元素分配新值时遇到问题_Python_For Loop_Iterator_Iteration_Variable Assignment - Fatal编程技术网

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

在python中使用for循环为迭代器的元素分配新值时遇到问题,python,for-loop,iterator,iteration,variable-assignment,Python,For Loop,Iterator,Iteration,Variable Assignment,我在使用for循环为迭代器的元素分配新值时遇到问题。假设我们有以下列表: some_2d_list=[['mean','really','is','jean',], ['world'、'my'、'rocks'、'python']列表。reverse原地反转并返回None,因此 for items in some_2d_list: items = items.reverse() 撤消仍在某些\u 2d\u列表中的现有列表,并将无分配给项 当您在部分二维列表中的项目的中输入代码块时,项目

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

some_2d_list=[['mean','really','is','jean',],

['world'、'my'、'rocks'、'python']
列表。reverse
原地反转并返回None,因此

for items in some_2d_list:
    items = items.reverse()
撤消仍在
某些\u 2d\u列表中的现有列表
,并将
分配给

当您在部分二维列表中的项目的
中输入代码块时,
项目
是对仍在部分二维列表中的对象的引用。任何修改现有列表的操作都会影响一些二维列表。比如说

>>> 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')]

因此,我们在项目上使用任何其他就地方法,它会工作吗?奇怪的是,item+=“foo”适用于列表,而item=item+“foo”不适用@Sherafati-有点随意。
list
实现者对“+=”使用
extend
方法,extend在迭代器上工作。因此,即使
l+=range(10)
也可以工作。它与“+”并不对称,后者反对这样做,但它在美学上相当令人愉悦。