删除列表中的元素的方式
主要问题是有的时候会少删除
- 删除之后下标-1
- 添加到新列表
- 倒着删
- 使用切片
students=[{'name':'zhangsan','age':26,'tel':'15895898270','sex':'male','score':100},
{'name':'Jack','age':12,'tel':'15895812345','sex':'female','score':99},
{'name':'Marry','age':17,'tel':'15895888888','sex':'female','score':100},
{'name':"wangwu",'age':29,'tel':'15895891314','sex':'male','score':57},
{'name': "wangwu", 'age': 29, 'tel': '15895891314', 'sex': 'unknown', 'score': 57},
{'name':'lisi','age':15,'tel':'15895897501','sex':'unknown','score':23},
{'name':'Tony','age':19,'tel':'15895890308','sex':'male','score':89},
{'name':'Nancy','age':25,'tel':'15895891042','sex':'unknown','score':96},
{'name':'wanghu','age':24,'tel':'1589589999','sex':'unknown','score':35}]
1.删除之后下标-1
i=0
while i<len(students):
if students[i]['sex']=='unknown':
students.pop(i)
i-=1
i+=1
print(students)
for student in students:
print(student)
# 2.添加到新列表
new_students=[]
for student in students:
if student['sex']!='unknown':
new_students.append(student)
print(new_students)
for student in new_students:
print(student)
#3.倒着删
for i in range(len(students)-1,-1,-1):
if students[i]['sex'] =='unknown':
students.pop(i)
for student in students:
print(student)
#4.使用切片
count=0
for student in students[:]:
count+=1
if student['sex']=='unknown':
students.remove(student)
print(count)
for student in students:
print(student)