例如
d1 == {'inds': [9, 9, 1, 9, 8, 1],
'vals': [0.28, 0.84, 0.71, 0.03, 0.04, 0.75]}
d2 == {'inds': [0, 9, 9, 1, 3, 3, 9],
'vals': [0.26, 0.06, 0.46, 0.58, 0.42, 0.21, 0.53, 0.76]}
如何通过下面的函数返回公共索引?
find_common_inds(d1, d2) == [1, 9]
这是我的代码,但似乎不起作用
intersect = []
for key in d1.keys():
if key in d2.keys():
intersect.append(key)
print(intersect)
答案 0 :(得分:0)
您可以在平整的值列表上使用设置交集:
from itertools import chain
d1 = {'inds': [9, 9, 1, 9, 8, 1], 'vals': [0.28, 0.84, 0.71, 0.03, 0.04, 0.75]}
d2 = {'inds': [0, 9, 9, 1, 3, 3, 9], 'vals': [0.26, 0.06, 0.46, 0.58, 0.42, 0.21, 0.53, 0.76]}
print(set(chain.from_iterable(d1.values())).intersection(chain.from_iterable(d2.values())))
# {9, 1}
参考:
使用chain.from_iterable()对列表进行修饰。
答案 1 :(得分:0)
您可以将功能更改为:
def find_common_values_in_identical_keys(d1,d2,**kwargs):
if 'keyname' in kwargs:
kn = kwargs['keyname'] # this is hard :P and it would still allow a "key"
# that's not a hashable so it will crash donw below :/
if kn:
try:
return list(set(d1.get(kn, set())).intersection(d2.get(kn, [])))
except TypeError as e:
print("Bad keyname:", e)
else:
return [(k,find_common_values_in_identical_keys(d1,d2,keyname = k))
for k in set(d1.keys()).union(d2)]
d1 = {'inds': [9, 9, 1, 9, 8, 1],
'vals': [0.28, 0.84, 0.71, 0.03, 0.04, 0.75]}
d2 = {'inds': [0, 9, 9, 1, 3, 3, 9],
'vals': [0.26, 0.06, 0.46, 0.58, 0.42, 0.21, 0.53, 0.76]}
print(find_common_values_in_identical_keys(d1,d2,"inds"))
wich然后打印:
[9,1] # the order is random as sets are inheritently unordered
这也可以处理所有键的情况:
print(find_common_values_in_identical_keys(d1,d2))
输出:
[('vals', []), ('inds', [9, 1])]
返回(键名,[相同值的列表])的元组列表
您可能仍要防止d1
和d2
不是dict
的使用isinstance(...)
的人,并抛出ValueError
使其更加安全。< / p>