我有两个字典列表,分别命名为category和sub_category。

category = [{'cat_id':1,'total':300,'from':250},{'cat_id':2,'total':100,'from':150}]


sub_category = [{'id':1,'cat_id':1,'charge':30},{'id':2,'cat_id':1,'charge':20},{'id':3,'cat_id':2,'charge':30}]


如果charge0值相等,我想在sub_category中将total >= from的值更改为category

预期结果是:

sub_category = [{'id':1,'cat_id':1,'charge':0},{'id':2,'cat_id':1,'charge':0},{'id':3,'cat_id':2,'charge':30}]


我设法用这个来得到结果

for sub in sub_category:
    for cat in category:
        if cat['cat_id'] == sub['cat_id']:
            if cat['total'] >= cat['from']:
                sub['charge']=0


但是我想知道更好的方法。任何帮助将不胜感激。

最佳答案

这是一种方法。将类别更改为dict即可轻松循环播放。

例如:

category = [{'cat_id':1,'total':300,'from':250},{'cat_id':2,'total':100,'from':150}]
sub_category = [{'id':1,'cat_id':1,'charge':30},{'id':2,'cat_id':1,'charge':20},{'id':3,'cat_id':2,'charge':30}]

category = {i.pop('cat_id'): i for i in category}

for i in sub_category:
    if i['cat_id'] in category:
        if category[i['cat_id']]['total'] >= category[i['cat_id']]['from']:
            i['charge'] = 0
print(sub_category)


输出:

[{'cat_id': 1, 'charge': 0, 'id': 1},
 {'cat_id': 1, 'charge': 0, 'id': 2},
 {'cat_id': 2, 'charge': 30, 'id': 3}]

09-25 19:29