将嵌套列表与字典键进行比较,创建具有值之和的复合键“a+b”

2024-09-09 04:06:06 发布

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

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

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循环的情况下,有没有办法做到这一点? 附:代码还没有完成


Tags: 代码inl1列表forlenif字典
3条回答

您可以尝试下面的代码

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)

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

首先用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}

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

注意: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)

相关问题 更多 >