我有一个清单:
a_list
:
[{'score': 60, 'credit': 5, 'class': 'A01', 'subject': 'math'},
{'score': 70, 'credit': 5, 'class': 'A01', 'subject': 'music'},
{'score': 65, 'credit': 5, 'class': 'B01', 'subject': 'science'},
{'score': 35, 'credit': 5, 'class': 'C02', 'subject': 'math'}]
我从db查询(django)得到一个列表,每个subject
都有自己的pass_mark
pass_list = ClassData.objects.values('subject','pass_mark')
pass_list
:
[{'pass_mark': 50, 'subject_all': u'math'},
{'pass_mark':70, 'subject_all': u'science'},
{'pass_mark': 70, 'subject_all': u'music'}]
我必须比较a_list
以检查pass_mark
是否高于pass_list
所以结果列表是:
[{'score': 60, 'credit': 5, 'class': 'A01', 'subject': 'math'},
{'score': 70, 'credit': 5, 'class': 'A01', 'subject': 'music'}]
这是我的方法:
result_list = []
for a in a_list:
check = [x for x in pass_list if x['subject_all'] == a['subject']]
if a['score'] >= check[0]['pass_mark']:
result_list.append(a)
print result_list
我想知道有更快或更好的方法
因为a_list
将来会很大
答案 0 :(得分:1)
制作一个dict,keys
是主题,值为scores
:
l = [{'score': 60, 'credit': 5, 'class': 'A01', 'subject': 'math'},
{'score': 70, 'credit': 5, 'class': 'A01', 'subject': 'music'},
{'score': 65, 'credit': 5, 'class': 'B01', 'subject': 'science'},
{'score': 35, 'credit': 5, 'class': 'C02', 'subject': 'math'}]
l2 = [{'pass_mark': 50, 'subject_all': u'math'},
{'pass_mark': 70, 'subject_all': u'science'},
{'pass_mark': 70, 'subject_all': u'music'}]
sub = {dct["subject_all"]: dct["pass_mark"] for dct in l2}
result = [dct for dct in l if dct["score"] >= sub[dct["subject"]]]
print(result)
输出:
[{'credit': 5, 'score': 60, 'class': 'A01', 'subject': 'math'}, {'credit': 5, 'score': 70, 'class': 'A01', 'subject': 'music'}]
你只需要通过l2
进行一次传递来构建dict,然后在l
进行一次传递,并在其他位置继续工作,因此解决方案为O(n)
,而不是您自己的二次方法。理想情况下,如果您可以首先创建sub
dict,那么这将是最好的方法。