在Python中从列表中删除元素

在Python中从列表中删除元素

本文介绍了在Python中从列表中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python 3.4并只是学习基础知识,所以请多多包涵..

I'm using python 3.4 and just learning the basics, so please bear with me..

listA = [1,2]
for a in listA:
    listA.remove(a)
print(listA)

假设我得到一个空列表,但是得到的是一个值为'2'的列表.我用大号调试了代码.列表中的值的组合,并且当列表具有单个元素时,for循环退出.为什么没有从列表中删除最后一个元素??

What is suppose is I get an empty list, but what I get is a list with value '2'. I debugged the code with large no. of values in list and when the list is having a single element the for loop exit.Why is the last element not removed from the list..?

推荐答案

在迭代列表时,请勿更改列表.当您删除项目时,列表的索引会更改,因此某些项目将永远不会被评估.请改用列表理解,它会创建一个新列表:

You should not change a list while iterating over it. The indices of the list change as you remove items, so that some items are never evaluated. Use a list comprehension instead, which creates a new list:

[a for a in list if ...]

换句话说,尝试这样的事情:

In other words, try something like this:

>>> A = [1, 2, 3, 4]
>>> A = [a for a in A if a < 4]       # creates new list and evaluates each element of old
>>> A
[1, 2, 3]

使用for循环时,将使用内部计数器.如果在迭代list时将剩余元素向左移动,则不会评估剩余list中最左边的元素.请参见注释,了解for语句.

When you use a for-loop, an internal counter is used. If you shift the remaining elements to the left while iterating over the list, the left-most element in the remaining list will be not be evaluated. See the note for the for statement.

这篇关于在Python中从列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:15