[英]Most efficient way to subtract between two list in every common keys between two python dictionaries
So i have two dictionaries, and for their common keys, i want to find the difference in each elements of the respective lists, the order does not matter in the output.所以我有两个字典,对于它们的公共键,我想找到各个列表的每个元素的差异,output 中的顺序无关紧要。
Here's a small example这是一个小例子
x={
'1' : [1,2,3],
'2' : [2,9]
}
y={
'1' : [4,5],
'3' : [8,9]
}
# Common key is '1' , so z is the list of the subtraction of elements of key '1'
>> expected_output = [-3, -2, -1, -4, -3, -2]
= [1-4,2-4,3-4, 1-5,2-5,3-5]
Here is an example of setting up bigger dictionaries with many common keys and uncommon keys这是一个使用许多常用键和不常用键设置更大字典的示例
import random
x={}
y={}
num_same_keys = 100
num_diff_keys = 200
## Generating common keys with arbitrary number of elements
common_key = random.randint(0,10000)
for _ in range(num_same_keys) :
while common_key in x : common_key = random.randint(0,10000)
x[common_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]
y[common_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]
## Generating different keys with arbitrary number of elements
x_key = random.randint(0,10000)
y_key = random.randint(0,10000)
for _ in range(num_diff_keys) :
# Adding to x
while (x_key in x) and (x_key in y) : x_key = random.randint(0,10000)
x[x_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]
# Adding to y
while (y_key in x) and (y_key in y) : y_key = random.randint(0,10000)
y[y_key] = [ random.randint(0,1000) for _ in range(random.randint(1,10)) ]
Currently i tried my best to optimise it by calling
&
on the keys as a set, then extend the list for each of them.目前,我尽我所能通过在键上调用&
作为一组来优化它,然后为每个键扩展列表。 However i'm not sure if its the most optimal.但是我不确定它是否是最优化的。
def f1(x,y):
z = []
for element in x.keys() & y.keys():
z.extend([xval-yval for xval in x[element] for yval in y[element] ])
return z
outputlist = f1(x,y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.