词典搜索列表

2024-03-28 23:45:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典清单如下

list1 = [{'3': ['0'], '10': ['2'], '9': ['8'], '6': ['8']},
         {'3': ['5'], '9': ['0'], '2': ['3']},
         {'2':['10'],'10':['8'],'4' :['9']}]

我还有另外一张单子

list2 = [0,1,2,3,5,6,7,8,9,10]

我想检查list2的每个值是否是list1的任何字典的键,然后如果它与键匹配,那么我希望所有值都与这些键关联并添加这些值。我如何在python中以非常优化的方式实现这一点,因为我的字典列表非常大。你知道吗


Tags: 列表字典方式单子list2list1
1条回答
网友
1楼 · 发布于 2024-03-28 23:45:52

因为你的字典列表实在太大了,所以预处理是必要和有效的。你知道吗

SumKey = {}
for item in list1:
    for key in item.keys():
        if key not in SumKey:
            SumKey[key] = 0
        SumKey[key] += item[key]

SumList = []
for item in list2:
    if item in SumKey.keys():
        SumList.append(SumKey[item])
    else:
        SumList.append(0)
网友
2楼 · 发布于 2024-03-28 23:45:52

上面的答案是非常Python,可能有点迟钝。你知道吗

这有点可读性(但不是最好的!)地址:

list1=[{'3': ['0'], '10': ['2'], '9': ['8'], '6': ['8']},\
       {'3': ['5'], '9': ['0'], '2': ['3']},\
       {'2':['10'],'10':['8'],'4' :['9']}]

list2 = [0,1,2,3,5,6,7,8,9,10]
strlist2 = [str(x) for x in list2]

total = 0
for subdict in list1:
    filtered = [v for k, v in subdict.items() if k in strlist2]

    print(filtered)

    for sublist in filtered:
        print(sublist)

        for val in sublist:
            total += int(val)

print(total)
网友
3楼 · 发布于 2024-03-28 23:45:52
from collections import defaultdict
dct = defaultdict(list)
for x in list1:
    for y,z in x.items():
        dct[int(y)].append(int(z[0]))
for x in list2:
    if x in dct:
        print sum(dct[x])

相关问题 更多 >