列表和字典在循环操作(增删)时,其长度会改变
# 删除 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)