#根据name删除信息 stu_list = [ {'name':'杨杨','age':'12','QQ':'6199'}, {'name':'喜羊羊','age':'16','QQ':'2471'}, {'name':'懒洋洋','age':'18','QQ':'3569'}
方法一:遍历列表,把字典中包含要删除的值不拼接到新列表
def appName(stu_list):
new_list = []
del_name = input('请输入你要删除信息的姓名:')
for stu_dict in stu_list:
if stu_dict['name'] != del_name:
new_list.append(stu_dict)
return print(new_list)
print(stu_list)
appName(stu_list)
运行结果为:
[{'name': '杨杨', 'age': '12', 'QQ': '6199'}, {'name': '喜羊羊', 'age': '16', 'QQ': '2471'}, {'name': '懒洋洋', 'age': '18', 'QQ': '3569'}]
请输入你要删除信息的姓名:杨杨
[{'name': '喜羊羊', 'age': '16', 'QQ': '2471'}, {'name': '懒洋洋', 'age': '18', 'QQ': '3569'}]
方法二:遍历列表,找到要删除的值的下标,删除列表下标对应的值
def delName(stu_list):
i = -1 #下标指向值
del_name = input('请输入你要删除信息的姓名:')
for stu_dict in stu_list:
i += 1 #每遍历一次,下标加一
if del_name in stu_dict['name']:
break #找到了该值,跳出循环
del stu_list[i]
return print(stu_list)
print(stu_list)
delName(stu_list)
运行结果为:
[{'name': '杨杨', 'age': '12', 'QQ': '6199'}, {'name': '喜羊羊', 'age': '16', 'QQ': '2471'}, {'name': '懒洋洋', 'age': '18', 'QQ': '3569'}]
请输入你要删除信息的姓名:喜羊羊
[{'name': '杨杨', 'age': '12', 'QQ': '6199'}, {'name': '懒洋洋', 'age': '18', 'QQ': '3569'}]