python之常见的坑

li = [1,2,3,4]  # [1,3,4]
# 索引值是奇数的删除
for i in range(4):
    if i % 2 == 1:
        li.pop(i)   # 会报错
print(li)

面试题:
li = [1,2,3,4,5]   #[1,3,4,5]
# 索引值是奇数的删除
for i in range(4):
    if i % 2 == 1:
        li.pop(i)   # 结果不对
print(li)


li = [1,2,3,4,5]
for i in range(len(li)-1,-1,-1):
    if i % 2 == 1:
        li.pop(i)   # 倒序删除
print(li)

偷换感念
li = [1,2,3,4,5]
new_li = []
for i in range(len(li)):
    if i % 2 == 1:
        new_li.append(li[i])
for em in new_li:
    li.remove(em)
print(li)

li = [1,2,3,4,5]
for i in range(len(li)-1,-1,-1):
    if i % 2 == 1:
        del li[i]   # 倒序删除
print(li)

li = [1,2,3,4,5]
del li[1::2]
print(li)

使用for删除列表的时候从左向右删除,会报错.结果不对

dic = {"k1":"v1","k2":"v2"}
for i in dic:
    dic["k3"] = "v3"
print(dic)

面试题:
li = [1,2,3,4]
for i in li:
    li.append(i)
print(li)

不能在遍历字典本身中改变大小,要批量删除字典的键值对

dic = {"k1":"v1","k2":"v2","k3":"v3"}
for i in dic:
    dic["k7"] = "1"
print(dic)

li = []
for i in dic:
    if i == "k1" or i == "k3":
        li.append(i)
for em in li:
    dic.pop(em)
print(dic)
posted @ 2019-06-12 21:47  爱咋闹  阅读(336)  评论(0编辑  收藏  举报