在Python中删除列表的最后一个元素失败(Removing last element of a list in Python fails)

编程入门 行业动态 更新时间:2024-10-27 14:29:13
在Python中删除列表的最后一个元素失败(Removing last element of a list in Python fails)

我试图删除Python中列表的最后一个元素:

di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} for el in di['children']: di['children'].remove(el)

我期望的是

print di {'a': 3, 'children: []}

但我得到的是

print di {'a': 3, 'children': [{'c': 6}]}

有没有人知道发生了什么问题?

I'm trying to remove the last element of a list in Python:

di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} for el in di['children']: di['children'].remove(el)

What I'd expect is

print di {'a': 3, 'children: []}

But what I get is

print di {'a': 3, 'children': [{'c': 6}]}

Does anybody have an idea what's going wrong?

最满意答案

正如其他人所解释的,在迭代它的时候你不能修改列表。

您可以在遍历副本时修改列表,但最好生成一个新的过滤列表:

di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} di['children'] = [el for el in di['children'] if el not in di['children']]

为什么这更好? 那么,这意味着您要避免变更列表,这会让您的代码更容易推理,更易于追踪,通常更易于编写,并且通常更快,更节省空间。 事实上,您不必担心迭代中出现变异问题,这是“易于推理”部分的完美例子。

在某些情况下,写起来会更困难,或者更慢,或者空间效率更低,这就是为什么这只是一个指导方针,而不是一个硬性规则。 但总是至少值得思考的是,“我可以将其重写为不可变过滤器而不是增变器”,即使答案有时可能会变成“不”。

还有,真的,你的算法不是保证等于只是清空整个事情吗? 在这种情况下:

di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} di['children'] = []

As everyone else has explained, you can't modify a list while iterating over it.

You can modify a list while iterating over a copy of it, but it's probably better to just generate a new filtered list:

di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} di['children'] = [el for el in di['children'] if el not in di['children']]

Why is this better? Well, it means you're avoiding mutating the list, which makes your code easier to reason about, easier to trace through, usually easier to write, and often faster and more space-efficient. The fact that you don't have to worry about mutating-while-iterating problems is a perfect example of the "easier to reason about" part.

In some cases, it does turn out to be harder to write, or slower, or less space-efficient, which is why this is just a guideline rather than a hard rule. But it's always at least worth thinking "can I rewrite this as an immutable filter instead of a mutator", even if the answer may sometimes turn out to be "no".

Also really, isn't your algorithm guaranteed to be equivalent to just emptying the whole thing out? In that case:

di = {"a": 3, "children": [{"b": 5}, {"c": 6}]} di['children'] = []

更多推荐

本文发布于:2023-08-03 03:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表   Python   Removing   fails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!