列表删除列表中的类实例上的函数不能正常工作

时间:2017-11-17 03:01:11

标签: 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,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'?

2 个答案:

答案 0 :(得分:1)

您正在尝试在迭代列表时删除数据。尝试理解:

final_data = [bt for bt in bts if bt.text != "123"]
for i in final_data:
   print(i.text)

输出:

3r5
1fe
3r5
1fe

答案 1 :(得分:0)

您在迭代时删除列表中的元素。这意味着第一次通过循环,i == 1,所以123从列表中删除。然后for循环进入列表中的第二项,这不是3r5,而是123!然后从列表中删除,然后for循环继续到列表中的第三个项目,现在是5.依此类推。也许这样看起来更容易,用^指向i的值:

["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"]

在迭代列表时,没有好的方法可以改变列表的长度。