几个基础类型循环删除 old

把列表中所有姓周的⼈的信息删掉(此题有坑, 请慎重):

lst = ['周老二', '周星星', '麻花藤', '周扒皮']

结果: lst = ['麻花藤']

 

lst = ['周老二', '周星星', '麻花藤', '周扒皮']
for i in range(len(lst)-1,-1,-1):
    if lst[i][0] =='':
        lst.remove(lst[i])
print(lst)
删除姓周的
lst = ['周老二', '周星星', '麻花藤', '周扒皮']
for i in range(len(lst)-1,-1,-1):
    if lst[i][0] =='':
        lst.pop(i)
print(lst)

lst = ['周老二', '周星星', '麻花藤', '周扒皮']
lst1=[]
for i in lst:
    if i.startswith(''):
        lst1.append(i)
for j in lst1:
        lst.remove(j)
print(lst)
删除 周

清空

lst = ['周老二', '周星星', '麻花藤', '周扒皮']
for i in range(len(lst)-1,-1,-1):
        lst.pop(i)
print(lst)
 直接删空
for i in range(len(lst)-1,-1,-1):
        lst.remove(lst[i])
print(lst)
直接删空


lst = ['周老二', '周星星', '麻花藤', '周扒皮']
for i in range(len(lst)):
    lst.remove(lst[i])
print(lst)     # 报错:IndexError: list index out of range
原文地址:https://www.cnblogs.com/lida585/p/10296173.html