赞
踩
alist = [{"ID": "001", "name": "111"},
{"ID": "002", "name": "222"},
{"ID": "002", "name": "333"},
{"ID": "002", "name": "444"},
{"ID": "001", "name": "555"},
{"ID": "001", "name": "666"},
{"ID": "001", "name": "777"},
{"ID": "001", "name": "888"},
{"ID": "001", "name": "999"},]
for i in alist:
if i["ID"] == "001":
alist.remove(i)
因为列表自动收缩,保证列表元素没有间隙,所以,这种办法删除列表内的元素时,会产生有间隔的for循环,会漏删除
newlist = list()
for i in alist:
if i["ID"] != "001":
newlist.append(i)
使用filter()函数也可以解决:
newlist = filter(lambda x: x["ID"] != "001", alist)
print(list(newlist))
# 可以使用for循环:
for i in newlist:
print(i)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。