迭代时修改列表 [英] Modify a list while iterating

查看:130
本文介绍了迭代时修改列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在迭代列表时不应添加/删除项目。但是,如果我不更改列表长度,我可以修改列表中的项目吗?

I know you should not add/remove items while iterating over a list. But can I modify an item in a list I'm iterating over if I do not change the list length?

class Car(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return type(self).__name__ + "_" + self.name

my_cars = [Car("Ferrari"), Car("Mercedes"), Car("BMW")]
print(my_cars)  # [Car_Ferrari, Car_Mercedes, Car_BMW]
for car in my_cars:
    car.name = "Moskvich"
print(my_cars)  # [Car_Moskvich, Car_Moskvich, Car_Moskvich]

或者我应该迭代列表索引而不是?像那样:

Or should I iterate over the list indices instead? Like that:

for car_id in range(len(my_cars)):
    my_cars[car_id].name = "Moskvich"

问题是:是允许以上两种方式还是只有第二种方式没有错误?

The question is: are the both ways above allowed or only the second one is error-free?

如果答案是肯定的,那么以下代码段是否有效?

If the answer is yes, will the following snippet be valid?

lovely_numbers = [[41, 32, 17], [26, 55]]
for numbers_pair in lovely_numbers:
    numbers_pair.pop()
print(lovely_numbers)  # [[41, 32], [26]]

UPD。我希望看到python文档,它说允许这些操作,而不是某人的假设。

UPD. I'd like to see the python documentation where it says "these operations are allowed" rather than someone's assumptions.

推荐答案

你是修改列表,可以这么说。您只需修改列表中的元素。我不相信这是一个问题。

You are not modifying the list, so to speak. You are simply modifying the elements in the list. I don't believe this is a problem.

要回答你的第二个问题,确实允许这两种方式(因为你知道,因为你运行了代码),但它将取决于具体情况。内容是可变的还是不可变的?

To answer your second question, both ways are indeed allowed (as you know, since you ran the code), but it would depend on the situation. Are the contents mutable or immutable?

例如,如果要为整数列表中的每个元素添加一个,这将不起作用:

For example, if you want to add one to every element in a list of integers, this would not work:

>>> x = [1, 2, 3, 4, 5]
>>> for i in x:
...     i += 1
... 
>>> x
[1, 2, 3, 4, 5] 

确实, int s是不可变对象。相反,您需要迭代索引并更改每个索引处的元素,如下所示:

Indeed, ints are immutable objects. Instead, you'd need to iterate over the indices and change the element at each index, like this:

>>> for i in range(len(x)):
...     x[i] += 1
...
>>> x
[2, 3, 4, 5, 6]

如果你的物品是可变的,然后第一个方法(直接迭代元素而不是索引)毫无疑问更有效,因为索引的额外步骤是一个可以避免的开销,因为这些元素是可变的。

If your items are mutable, then the first method (of directly iterating over the elements rather than the indices) is more efficient without a doubt, because the extra step of indexing is an overhead that can be avoided since those elements are mutable.

这篇关于迭代时修改列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆