简体   繁体   English

Python:如何删除列表中 class 的每个实例?

[英]Python:How do I delete every instance of a class in a list?

I'm trying to delete every instance of a class in a for loop.我正在尝试在for循环中删除 class 的每个实例。 However, there is a point in which the list length meets the for loop iteration.但是,有一点是列表长度满足for循环迭代的地方。 See:看:

 for n in range(len(myList)): print(len(myList), n) del myList[n]

Output: Output:

15 0
14 1
13 2
12 3
11 4
10 5
9 6
8 7
7 8
IndexError: list assignment index out of range`

The only solution that came across my head so far was to create a variable for each item in the list and deleting them that way, but I've heard that's usually not something you need to do.到目前为止,我想到的唯一解决方案是为列表中的每个项目创建一个变量并以这种方式删除它们,但我听说这通常不是你需要做的事情。 Any ideas on how I can achieve this?关于如何实现这一目标的任何想法?

One way is to step through the list backwards.一种方法是向后逐步浏览列表。

for n in range (len (myList) -1, -1, -1):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM