动态删除列表中的元素
对于一个长度变化的数据类型来说,索引也是
(面试题)要删除li = [11,22,33,44,55]索引为奇数的元素。
第一种: count = 0 for i in range(0,len(li)): if i%2 == 1: del li[i - count] count += 1 print(li)
第二种: for i in range(0,len(li)//2): del li[i+1] print(li)
第三种: for i in range(len(li)-1,0,-1): if i%2 == 1: del li[i] print(li)
(面试题)删除字典中含有k的键:
dic = {'k1':'barry','k2':'alex','name':'ritian'}
如果按照一般的循环删除肯定会出错。
Traceback (most recent call last): File "I:/untitled/cx/10-25/编码.py", line 44, in <module> for i in dic.keys(): RuntimeError: dictionary changed size during iteration
参考答案:
lis = [] for i in dic: if 'k' in i: lis.append(i) for i in lis: del dic[i] print(dic) del lis