Python 列表中的类实例上的list remove函数工作不正常
这是代码,我很困惑:Python 列表中的类实例上的list remove函数工作不正常,python,list,class,instance,Python,List,Class,Instance,这是代码,我很困惑: class Button(): def __init__(self, text): self.text = text bt1 = Button('123') bt2 = Button('3r5') bt3 = Button('123') bt4 = Button('1fe') bt5 = Button('123') bts = [] bts.extend((bt1,bt2,bt3,bt4,bt5)) bts.extend((bt1,bt2,bt
class Button():
def __init__(self, text):
self.text = text
bt1 = Button('123')
bt2 = Button('3r5')
bt3 = Button('123')
bt4 = Button('1fe')
bt5 = Button('123')
bts = []
bts.extend((bt1,bt2,bt3,bt4,bt5))
bts.extend((bt1,bt2,bt3,bt4,bt5))
for bt in bts:
if bt.text == '123':
bts.remove(bt)
for bt in bts:
print(bt.text)
结果如下:
3r5
1fe
123
3r5
1fe
我的问题是,为什么有一个带有文本“123”的元素没有被删除?您在迭代列表时试图删除数据。试着理解一下:
final_data = [bt for bt in bts if bt.text != "123"]
for i in final_data:
print(i.text)
输出:
3r5
1fe
3r5
1fe
您在迭代列表时删除了列表中的元素。这意味着第一次通过循环时,i==1,因此从列表中删除123。然后for循环转到列表中的第二项,它不是3r5,而是123!然后从列表中删除它,然后for循环继续到列表中的第三项,现在是5。等等也许这样更容易想象,用^表示i的值:
在遍历列表时,没有好的方法可以改变列表的长度 你不应该在迭代列表时修改它们…@Shadow明白了!谢谢明白了,谢谢@文昌利如果这个答案对你有帮助,请接受它。@Ajax1234你还没有给出它奇怪行为的原因,为什么它不删除这个123
["123", "3r5", "123", "123", "1fe"]
^
That's the state of the list initially; then 1 is removed and the loop goes to the second item in the list:
["3r5", "123", "123", "1fe"]
^
[ "3r5", "123", "1fe"]
^
so remaining elements after loop ends [ "3r5", "123"]