问题描述
当我意识到del似乎不起作用时,我正在遍历带有for循环的列表。我认为这是因为我代表的是for循环的对象,而del只是删除该对象而不是引用。
I was iterating through a list with a for loop, when I realized del seemed to not work. I assume this is because i is representing an object of the for loop and the del is simply deleting that object and not the reference.
但是,我确定我已经
alist = [6,8,3,4,5]
for i in alist:
if i == 8:
del i
在我的代码中实际上是一个字符串列表,但结果是相同的:即使满足条件,删除i也无效。
In my code its actually a list of strings, but the result is the same: even though the if conditional is satisfied, deleting i has no effect.
有没有办法我可以用这种方式删除数字或字符串?我在做错什么吗?
Is there a way I can delete a number or string in this way? Am I doing something wrong?
谢谢。
推荐答案
您的想法关于为什么您看到这种行为是正确的。因此,我将不再赘述。
Your idea as to why you are seeing that behavior is correct. Hence, I won't go over that.
要执行您想要的操作,请使用可以过滤列表:
To do what you want, use a list comprehension to filter the list:
>>> alist = [6,8,3,4,5]
>>> [x for x in alist if x != 8]
[6, 3, 4, 5]
>>> alist = [6,8,8,3,4,5]
>>> [x for x in alist if x != 8]
[6, 3, 4, 5]
>>>
这种方法也比for循环更有效。
This approach is also a lot more efficient than a for-loop.
这篇关于Python:在del中使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!