#1.索引为奇数值,删除 # 删除列表元素时,会影响列表长度,从而使得索引取值时,容易出现错误。 li = [11, 22, 33, 44, 66] li = [11, 22, 33, 44, 66] # 0 # 索引为奇数值,删除 for i in range(0, len
# 删除列表元素时,会影响列表长度,从而使得索引取值时,容易出现错误。
li = [11, 22, 33, 44, 66]
li = [11, 22, 33, 44, 66] # 0
# 索引为奇数值,删除
for i in range(0, len(li)): # 4,0
del li[i]
print(li)
# 解决方案一:
# li = [11, 22, 33, 44, 66] # 0
# new_list = []
# # 索引为奇数值,删除
# for i in range(0,len(li)):
# if i%2 == 0:
# new_list.append(li[i])
# li = new_list
# print(li)
# 解决方案二:
# li = [11, 22, 33, 44, 66] # 0
# # 索引为奇数值,删除
# for i in range(len(li)-1,-1,-1): # 4,0
# if i%2 == 1:
# del li[i]
# print(li)
dict删除时需要注意
# 出错点# 题:dic = {'k1':"v1",'k2':'v2'}把key="k1",键值对删除
# del dic['k1']
# 题:dic = {'u1':"v1",'k2':'v2','k3':'v3'}把key中存在k,键值对删除
#
dic = {'u1': "v1", 'k2': 'v2', 'k3': 'v3'}
# 不要在循环当前字典的过程中,修改当前字典大小
# 错误
# for key in dic:
# if 'k' in key:
# del dic[key]
# 正确方式
dic_key_list = []
for key in dic:
dic_key_list.append(key)
for row in dic_key_list:
if 'k' in row:
del dic[row]
print(dic)