diz*_*cza 6 python iteration list
我知道你不应该在迭代列表时添加/删除项目.但是,如果我不更改列表长度,我可以修改列表中的项目吗?
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]
Run Code Online (Sandbox Code Playgroud)
或者我应该迭代列表索引而不是?像那样:
for car_id in range(len(my_cars)):
my_cars[car_id].name = "Moskvich"
Run Code Online (Sandbox Code Playgroud)
问题是:上述两种方式是允许的,还是只有第二种方式没有错误?
如果答案是肯定的,那么以下代码段是否有效?
lovely_numbers = [[41, 32, 17], [26, 55]]
for numbers_pair in lovely_numbers:
numbers_pair.pop()
print(lovely_numbers) # [[41, 32], [26]]
Run Code Online (Sandbox Code Playgroud)
UPD.我想看看python文档,它说"允许这些操作",而不是某人的假设.
cs9*_*s95 16
你没有修改列表,可以这么说.您只需修改列表中的元素.我不相信这是一个问题.
要回答你的第二个问题,确实允许这两种方式(正如你所知,因为你运行了代码),但这取决于具体情况.内容是可变的还是不可变的?
例如,如果要向整数列表中的每个元素添加一个,这将不起作用:
>>> x = [1, 2, 3, 4, 5]
>>> for i in x:
... i += 1
...
>>> x
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
实际上,ints是不可变的对象.相反,您需要迭代索引并更改每个索引处的元素,如下所示:
>>> for i in range(len(x)):
... x[i] += 1
...
>>> x
[2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
如果你的项是可变的,那么第一种方法(直接迭代元素而不是索引)毫无疑问会更有效,因为索引的额外步骤是一个可以避免的开销,因为这些元素是可变的.
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?
You're not modifying the list in any way at all. What you are modifying is the elements in the list; That is perfectly fine. As long as you don't directly change the actual list, you're fine.
There's no need to iterate over the indices. In fact, that's unidiomatic. Unless you are actually trying to change the list itself, simply iterate over the list by value.
If the answer is yes, will the following snippet be valid?
Run Code Online (Sandbox Code Playgroud)lovely_numbers = [[41, 32, 17], [26, 55]] for numbers_pair in lovely_numbers: numbers_pair.pop() print(lovely_numbers) # [[41, 32], [26]]
Absolutely. For the exact same reasons as I said above. Your not modifying lovely_numbers itself. Rather, you're only modifying the elements in lovely_numbers.
| 归档时间: |
|
| 查看次数: |
12017 次 |
| 最近记录: |