我认为这就是你想要的内容:
import numpy as np
d = {
(1.0, 1.0): [1, 2, 3, 4],
(1.0, 2.5): [2, 3, 4, 5],
(1.0, 3.75): [],
(1.5, 1.0): [8, 9, 10],
(1.5, 2.5): [2, 6, 8, 19, 1, 31],
(1.5, 3.75): [4]
}
indices = np.array(
[
[[(1.0, 1.0), (1.0, 3.75)], [(1.5, 1.0), (1.5, 3.75)]],
[[(1.0, 2.5), (1.5, 1.0)], [(1.5, 2.5), (1.5, 3.75)]]
])
for group in indices:
print('not: ', group.flatten())
print('but: ', group.reshape(-1, group.shape[-1]))
for group in indices:
group = group.reshape(-1, group.shape[-1])
values = list(x for key in group for x in d[tuple(key)])
print(values)
result = [
(min(vals), max(vals)) for vals in (
list(x for key in grp.reshape(-1, grp.shape[-1]) for x in d[tuple(key)])
for grp in indices
)
]
print(result)
输出:
not: [1. 1. 1. 3.75 1.5 1. 1.5 3.75]
but: [[1. 1. ]
[1. 3.75]
[1.5 1. ]
[1.5 3.75]]
not: [1. 2.5 1.5 1. 1.5 2.5 1.5 3.75]
but: [[1. 2.5 ]
[1.5 1. ]
[1.5 2.5 ]
[1.5 3.75]]
[1, 2, 3, 4, 8, 9, 10, 4]
[2, 3, 4, 5, 8, 9, 10, 2, 6, 8, 19, 1, 31, 4]
[(1, 10), (1, 31)]
也就是说,[(1, 10), (1, 31)]
就是您想要的结果,其中 1
是第一组索引的组合值中最小值,10
是同一组数值的最大值,等等。
以下是一些关键行的解释:
values = list(x for key in group for x in d[tuple(key)])
该代码通过循环遍历组中每对键/值对,并使用它们作为字典d的索引来构建一个组合值列表。但是,由于在重新整形后键将成为一个ndarray,因此首先将其传递给tuple()函数,以便正确地索引dict。它循环遍历检索到的值,并将每个值x添加到结果列表中。
解决方案在单个推导式中完成:
[
(min(vals), max(vals)) for vals in (
list(x for key in grp.reshape(-1, grp.shape[-1]) for x in d[tuple(key)])
for grp in indices
)
]
外层括号表示正在构建一个列表。 (min(vals),max(vals))
是vals
的最小值和最大值的元组,vals
循环遍历内部推导式。 内部推导式是一个生成器(用圆括号而不是方括号),为indices
中每个组生成列表,就像上面解释的那样。
编辑:您更新了问题,添加了 dtype
到索引中,使其成为结构化数组,如下所示:
indices = np.array(
[
[[(1.0, 1.0), (1.0, 3.75)], [(1.5, 1.0), (1.5, 3.75)]],
[[(1.0, 2.5), (1.5, 1.0)], [(1.5, 2.5), (1.5, 3.75)]]
], dtype='float16,float16')
为了应对这种变化并使解决方案仍然可行,您可以简单地使用非结构化副本进行操作:
unstructured_indices = rf.structured_to_unstructured(indices)
for group in unstructured_indices:
group = group.reshape(-1, group.shape[-1])
values = list(x for key in group for x in d[tuple(key)])
print(values)
解决方案如下:
result = [
(min(vals), max(vals)) for vals in (
list(x for key in grp.reshape(-1, grp.shape[-1]) for x in d[tuple(key)])
for grp in rf.structured_to_unstructured(indices)
)
]