我想检查列表中的dicts格式为:
class
,subject
,teacher
但我得到了奇怪的结果:
如果1 {'subject':'history','teacher':'Marry'}
无效
但代码没有删除它!
案例2运作良好
以下是我的工作:
# case 1
data_list = [{'class':'A','subject':'math','teacher':'Sam'},
{'class':'','subject':'','teacher':''},
{'subject':'history','teacher':'Marry'}]
# case 2
# data_list = [{'teacher': 'Marry', 'subject': 'D'}]
for data in data_list:
message={}
message['class'] = data.get('class',required_field) or blank_field
message['subject'] = data.get('subject',required_field) or blank_field
message['teacher'] = data.get('teacher',required_field) or blank_field
if required_field in message.values() or blank_field in message.values():
print "This dict need to be remove:{}".format(message)
data_list.remove(data)
print "#### final list ####"
print data_list
print "#### final list ####"
案例1结果:
This dict need to be remove:{'teacher': 'This_field_may_not_be_blank', 'class': 'This_field_may_not_be_blank', 'subject': 'This_field_may_not_be_blank'}
#### final list ####
[{'teacher': 'Sam', 'class': 'A', 'subject': 'math'},
{'teacher': 'Marry', 'subject': 'history'}]
#### final list ####
案例2结果:
This dict need to be remove:{'teacher': 'Marry', 'class': 'This_field_is_required', 'subject': 'D'}
#### final list ####
[]
#### final list ####
答案 0 :(得分:2)
AJK已经指出了您的代码出了什么问题,但您也可以缩短它,因此更容易理解。请记住,如果给定的键不在dict中,并且get
和空字符串None
评估为false,则字典None
方法将返回""
因此,最简单的方法是创建一个可接受条目的新列表,如下所示:
result = []
for d in data_list:
if d.get("class") and d.get("subject") and d.get("teacher"):
result.append(d)
您可以通过使用理解来缩短这一点:
result = [d for d in data_list
if d.get("class") and d.get("subject") and d.get("teacher")]
答案 1 :(得分:0)
这是因为您永远不应该使用for
从您正在迭代的列表中删除项目。
以下是一个类似的模块:problem Deleting list items in a for loop (python)
使用th copy
模块。 copied_list = copy.deepcopy(original_list)