运行此代码时,我希望它返回dict1的键1和3,但它仅返回第一个键。我需要它从dict1返回每个键/值迭代的所有匹配项。感谢您的帮助!
dict1={1:[(3.5, 7.8),(1.5, 2.5)], 2: [(6.3, 8.5)], 3:[(3.4,5.6)]}
dict2={1:[(1.5, 2.5), (3.5, 7.8)], 2: [(2.3, 1.5)], 3:[(3.4,5.6)]}
for k, v in dict1.items():
if set(v).issubset(set(next(iter(dict2.values())))):
print(k, v)
答案 0 :(得分:1)
您的代码问题非常明显:
for k, v in dict1.items():
if set(v).issubset(set(next(iter(dict2.values())))):
print(k, v)
next(iter(dict2.values())
仅获得第一个值。如果要迭代所有值,则必须实际迭代所有值:
for k, v in dict1.items():
for v2 in dict2.values():
if set(v).issubset(set(v2)):
print(k, v)
break
如果您真的想在工作后将其压缩成单线,则可以:
for k, v in dict1.items():
if any(set(v).issubset(set(v2)) for v2 in dict2.values()):
print(k, v)
无论哪种方式,您都可能希望将set(v)
置于循环之外,
for k, v in dict1.items():
v = set(v)
if any(v.issubset(set(v2)) for v2 in dict2.values()):
print(k, v)
我们正在努力,您是否真的需要子集测试?您所有的示例元组都是2元组,因此v.issubset(v2)
是对v == v2
的情况。测试起来更简单:
for k, v in dict1.items():
v = set(v)
if any(v == set(v2) for v2 in dict2.values()):
print(k, v)
或者:
for k, v in dict1.items():
if set(v) in {set(v2) for v2 in dict2.values()}:
print(k, v)
或者:
for k, v in dict1.items():
if set(v) in map(set, dict2.values()):
print(k, v)
答案 1 :(得分:0)
>>> dict2_items = map(set, dict2.values())
>>> [(k,v) for k, v in dict1.items() if set(v) in dict2_items]
[(1, [(3.5, 7.8), (1.5, 2.5)]), (3, [(3.4, 5.6)])]