Python Tulpe Key for Dict Partial Lookup [英] Python Tulpe Key For Dict Partial Lookup
问题描述
D [i,j,k,g,h] = value。
需要使用某个部分密钥对(i1,g1)处理所有元素:
我现在需要每一对(i1,g1)所有的值为i == i1和g == g1在完整的键。
什么是pythonic和有效的方式来检索这个,知道我需要所有对的元素和每个完整的键属于正好一个部分键?
是否比字典更合适的数据结构?
一个参考实现是这样的:
results = {} $ b中的i
对于G中的g
结果[i,g] = []
对于i,j,k,g,h在D :
如果i1 == i和g1 == g:
结果[i,g] .append(D [i,j,k,g,h])
假设你知道不同索引的所有有效值,你可以得到所有可能 c code code
$ b
import itertools
I = [3,6,9]
J =范围(10)
K =abcde
G = [first,second]
H = range(10,20)
for tup in itertools.product(I,J,K,G,H):
my_dict [tup] = 0
限制生成的索引只对一个/几个生成的索引进行限制,例如所有的键, i = 6
将是:
itertools.product((6, ) J,K,G,H)
一个函数让你指定你想要所有的索引,其中 i == 6和g ==first
将如下所示:
def partial_indices(i_vals = I,j_vals = J,k_vals = K,g_vals = G,h_vals = H):
返回itertools.product(i_vals,j_vals,k_vals,g_vals,h_vals)
partial_indices(i_vals =(6,),g_vals =(first))
或者假设并非所有这些都存在于字典中,您也可以通过字典作为参数,并在生成密钥之前检查会员资格:
def items_with_partial_indices(d,i_vals = I,j_vals = J,k_vals = K,g_vals = G,h_vals = H):
for tup in itertools.product(i_vals,j_vals,k_vals,g_vals,h_vals ):
try:
yield tup,d [tup]
除了KeyError:
pass
I have a dictionary with a tuple of 5 values as a key. For example:
D[i,j,k,g,h] = value.
Now i need to process all elements with a certain partial key pair (i1,g1):
I need now for each pair (i1,g1) all values that have i == i1 and g == g1 in the full key.
What is an pythonic and efficient way to retrieve this, knowing that i need the elements for all pairs and each full key belongs to exactly one partial key?
Is there a more appropriate data structure than dictionaries?
One reference implementation is this:
results = {}
for i in I:
for g in G:
results[i,g] = []
for i,j,k,g,h in D:
if i1 == i and g1 == g:
results[i,g].append(D[i,j,k,g,h])
Assuming you know all the valid values for the different indices you can get all possible keys using itertools.product
:
import itertools
I = [3,6,9]
J = range(10)
K = "abcde"
G = ["first","second"]
H = range(10,20)
for tup in itertools.product(I,J,K,G,H):
my_dict[tup] = 0
To restrict the indices generated just put a limit on one / several of the indices that gets generated, for instance all of the keys where i = 6
would be:
itertools.product((6,), J,K,G,H)
A function to let you specify you want all the indices where i==6 and g =="first"
would look like this:
def partial_indices(i_vals=I, j_vals=J, k_vals=K, g_vals = G, h_vals = H):
return itertools.product(i_vals, j_vals, k_vals, g_vals, h_vals)
partial_indices(i_vals=(6,), g_vals=("first",))
Or assuming that not all of these are present in the dictionary you can also pass the dictionary as an argument and check for membership before generating the keys:
def items_with_partial_indices(d, i_vals=I, j_vals=J, k_vals=K, g_vals = G, h_vals = H):
for tup in itertools.product(i_vals, j_vals, k_vals, g_vals, h_vals):
try:
yield tup, d[tup]
except KeyError:
pass
这篇关于Python Tulpe Key for Dict Partial Lookup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!