创建 axes 对象(名称 ax)并用 Line2D 实例填充它后,我想从 axes.lines 中删除一个子集(包含这些 Line2D 实例),基于标签。
但是,当我迭代此列表并删除成员时,它在评估时会缩小,然后我得到错误的计数(事实上,是一半),因此我无法迭代其所有成员
from matplotlib import pyplot as plt
fig = plt.figure()
# creating axes object
ax = fig.add_subplot(111)
# adding plots (Line2D objects) to ax
N=30
for indx in range(N):
ax.plot(1,1,label="my_line")
# adding another plot so the list is not identical
ax.plot(1,1,label="not_my_line")
print("I've created", len(ax.lines), "lines")
# iterating on the whole ax.lines list
for i,line in enumerate(ax.lines):
if line.get_label() == "my_line":
ax.lines.remove(line)
print ("I've expected to delete",N,"of them, but only",i+1 ,"lines were iterated")
print ("The remaining list is still", len(ax.lines), "lines long")
最佳答案
你不应该永远操作你在Python中迭代的列表。另请参阅
- How to remove items from a list while iterating?
- Why can’t you modify lists through "for in" loops in Python?
这里一个简单的解决方案是迭代原始列表的(完整)切片:
for i,line in enumerate(ax.lines[:]):
关于python matplotlib 在axes.lines上迭代得到错误的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51382053/