【问题标题】:Trouble with assigning new values to the elements of an iterator using for loop in python在python中使用for循环为迭代器的元素分配新值的麻烦
【发布时间】:2020-08-10 19:38:35
【问题描述】:

我在使用 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"]]

【问题讨论】:

    标签: python for-loop iterator iteration variable-assignment


    【解决方案1】:

    list.reverse 原地反转并返回 None,所以

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

    【讨论】:

    • 所以我们对项目使用任何其他就地方法,它会起作用吗?
    • 奇怪的是 item+="foo" 适用于列表,但 item = item +"foo" 不适用!
    • @Sherafati - 有点随机。 list 实现者将 extend 方法用于“+=”并在迭代器上扩展工作。所以,即使l += range(10) 也有效。它与 "+" 不是对称的,它反对这样做,但它在美学上相当令人愉悦。
    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2015-06-06
    • 1970-01-01
    相关资源
    最近更新 更多