【发布时间】:2017-12-12 22:46:08
【问题描述】:
如何将具有公共值的字典键合并到元组中。例如:
A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}
output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}
我的尝试:
A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}
output = {}
seen = []
for k, v in A.items():
if v not in [s[1] for s in seen]: # not seen this value yet
print('NOT SEEN')
print(k, v)
seen.append([k,v])
output[k] = v
else: # already seen it
print('SEEN')
print(k, v)
# determine where we've seen it
where = [x for x in seen if x[1]==v]
output.pop(where[0][0])
output[(where[0][0], k)] = v
print('OUTPUT = ', output)
打印出来:
OUTPUT = {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}
【问题讨论】:
-
好的,是什么阻止你这样做?您有具体问题吗?
-
@vaultah 改写为一个问题
-
我们是说我们希望看到您的努力。 “给我代码”之类的问题通常不受欢迎。尤其是当一两个循环应该足以解决问题时。
-
@ApplePie 不一样
标签: python algorithm python-3.x dictionary merge