3 回答
TA贡献1951条经验 获得超3个赞
您不需要循环即可从中获取项目Dict2。只需使用Dict2[c].
Dict1 = { 'D1':[ 'C1', 'C2'], 'D2': ['C1'], 'D3': ['C2', 'C3'], 'D4': ['C3']}
Dict2 = { 'C1': [ ('W1', 1 ), ('W2', 5), ('W3', 4) ], 'C2': [ ('W3', 2), ('W4', 6) , ('W5', 7) ], 'C3':[ ('W6',0),( 'W1',4), ( 'W2', 8)], 'C4': [('W7',3 ),('W8', 8)]}
Dict3 = {}
for d, c_list in Dict1.items():
for c in c_list:
w = [item[0] for item in Dict2[c]]
Dict3[d] = Dict3.get(d, []) + w
print(Dict3)
TA贡献1777条经验 获得超3个赞
Dict1 = { 'D1':[ 'C1', 'C2'], 'D2': ['C1'], 'D3': ['C2', 'C3'], 'D4': ['C3']}
Dict2 = { 'C1': [ ('W1', 1 ), ('W2', 5), ('W3', 4) ], 'C2': [ ('W3', 2), ('W4', 6) , ('W5', 7) ], 'C3':[ ('W6',0),( 'W1',4), ( 'W2', 8)], 'C4': [('W7',3 ),('W8', 8)]}
Dict3 = {k: [ii for i in v for ii, _ in Dict2[i]] for k, v in Dict1.items()}
print(Dict3)
印刷:
{'D1': ['W1', 'W2', 'W3', 'W3', 'W4', 'W5'], 'D2': ['W1', 'W2', 'W3'], 'D3': ['W3', 'W4', 'W5', 'W6', 'W1', 'W2'], 'D4': ['W6', 'W1', 'W2']}
TA贡献2080条经验 获得超4个赞
我不确定是否有更快的解决方案,但它可以满足您的需求:
dict1 = {'D1':[ 'C1', 'C2'], 'D2': ['C1'], 'D3': ['C2', 'C3'], 'D4': ['C3']}
dict2 = {'C1': [('W1', 1), ('W2', 5), ('W3', 4) ], 'C2': [ ('W3', 2), ('W4', 6) , ('W5', 7) ], 'C3':[ ('W6',0), ('W1',4), ('W2', 8)], "C4": [('W7', 3),('W8', 8)]}
dict3 = {k: [t[0] for e in v for t in dict2[e]] for k, v in dict1.items()}
print(dict3)
输出:
{'D1': ['W1', 'W2', 'W3', 'W3', 'W4', 'W5'], 'D2': ['W1', 'W2', 'W3'], 'D3': ['W3', 'W4', 'W5', 'W6', 'W1', 'W2'], 'D4': ['W6', 'W1', 'W2']}
添加回答
举报