擅长:python、mysql、java
<p>类似于以下内容,使用生成器:</p>
<p>注意:OP如果你不澄清这个问题,我会删除这个</p>
<pre><code>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)
</code></pre>