for循環遍歷的是一開始的列表,每次都會找列表中的第i個元素
card_list = [['wong', '1', '1'], ['ben', '1', '1'], ['zhuzhu', '1', '1'], ['nannan', '1', '1']]
for card in card_list:
index = card_list.index(card)
del card_list[index]
print(card_list)
結果:[['ben', '1', '1'], ['nannan', '1', '1']]
原因:for遍歷列表是一開始索引下標為0-3的,逐漸減少數據,列表並沒有更新。
所以在刪除索引為0數據后,ben的索引變成了0,zhuzhu索引為1,按照遍歷就去刪除了索引為1的數據。
解決這個問題:
方法1:用while循環
i = 0
while i < len(card_list):
for card in card_list:
index = card_list.index(card)
del card_list[index]
方法2:切片
for card in card_list[ : ]:
index = card_list.index(card)
del card_list[index]