1. 程式人生 > >python中迴圈刪除list和dict型別注意事項

python中迴圈刪除list和dict型別注意事項

列表和字典在迴圈操作(增刪)時,其長度會改變

# 刪除 li = [11, 22, 33, 44, 'rock']中索引為單數的元素
# 方法一
del li[1::2]
print(li)   # [11, 33, 'rock']

# 方法二
new_li = []
for index in range(len(li)):
    print(index)
    if index % 2 == 0:
        new_li.append(li[index])
li = new_li
print(li)

# 方法三
# 取首不取尾
for index in range(len(li)-1, 0-1, -1):
    
print(index) if index % 2 != 0: li.pop(index) print(li) # 錯誤示例 for index in range(len(li)): print(index) if index % 2 != 0: li.pop(index) print(li)
# 刪除 dic = {'k1': 1, 'k2': 1, 'k3': 1, 'name': 'rock'}中所有包含k字母的鍵值對

# dict字典在迴圈時不能改變字典的長度,即不能增刪改查字典中的元素
dic = {'k1': 1, '
k2': 1, 'k3': 1, 'name': 'rock'} li = [] for key in dic.keys(): if 'k' in key: li.append(key) for i in li: dic.pop(i) print(dic) # {'name': 'rock'} # 錯誤示例 RuntimeError: dictionary changed size during iteration for key in dic.keys(): if 'k' in key: dic.pop(key) print(dic)
for key in dic.keys(): print(key[0]) if key[0] == 'k': dic.pop(key) print(dic)