繁体   English   中英

将嵌套列表与字典键进行比较,使用值的总和创建复合键 'a+b'

[英]Comparing nested list with dictionary keys, create compound key 'a+b' with sum of values

我有一个嵌套列表,我想将列表项与字典键进行比较,如果找到匹配项,则应将相应的字典值相加并附加到与新键值对相同​​的字典中。

l1 = [['a','b'], ['c','d']] 

dict1 = {'a':10, 'e':20, 'c':30, 'b':40}

预期结果:

dict1 = {'a':10, 'e':20, 'c':30, 'b':40, 'a+b':50, 'a+c':40, 'b+c':70}

到目前为止我做了什么:

for x in range(len(l1)):
    for y in range(len(l1[x])):
        for k in dict1.keys():
            if k == l1[x][y]:
                dict1.append(dict1[k])

有没有办法在不使用嵌套 for 循环的情况下做到这一点? PS:代码还没有完成。

假设您的嵌套列表不重要,例如l1可以更改为["a", "b", "c", d"]您可以在此处使用itertools

首先用itertools.chain压平l1

import itertools
l2 = itertools.chain(*l1)

(或l2 = itertools.chain.from_iterable(l1) )。

然后遍历两个元素的所有组合

for i, j in itertools.combinations(l2, 2):
    if i in dict1 and j in dict1:
        dict1[f"{i}+{j}"] = dict1[i] + dict1[j]

全部一起

import itertools 

l1 = [['a','b'], ['c','d']] 
dict1 = {'a':10, 'e':20, 'c':30, 'b':40}
 
for i, j in itertools.combinations(itertools.chain(*l1), 2):
    if i in dict1 and j in dict1:
        dict1[f"{i}+{j}"] = dict1[i] + dict1[j]

dict1现在将等于

{'a': 10, 'e': 20, 'c': 30, 'b': 40, 'a+b': 50, 'a+c': 40, 'b+c': 70}

你可以试试下面的代码

dict1 = {'a':10, 'e':20, 'c':30, 'b':40, 'a+b':50, 'a+c':40, 'b+c':70}
dict2={}
dict2['a+b']=dict1['a']+dict1['b']
dict2['a+c']=dict1['a']+dict1['c']
dict2['b+c']=dict1['b']+dict1['c']
dict1.update(dict2)
print(dict1)

类似于以下内容,使用生成器:

注意:OP,如果您不澄清问题,我将删除此问题

d = {'a':10, 'e':20, 'c':30, 'b':40}
l1 = [['a','b'], ['c','d']]

def _gen_compound_keys(d, kk):
    """Generator helper function for the single and ocmpound keys from input tuple of keys"""
    # Note: you can trivially generalize this from assuming fixed length of 2
    yield kk[0], d[kk[0]]
    yield kk[1], d[kk[1]]
    yield '+'.join(kk), sum(d[k] for k in kk)

def gen_compound_keys(d, kk):
    """Generator for the single and compound keys, returns a dictionary as desired"""
    return {k:v for k,v in _gen_compound_keys(d, kk)}

result = {}
result.update(gen_compound_keys(d, l1[0]))
result.update(gen_compound_keys(d, l1[1]))
result.update(d)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM