基本原理
最简单、最有效的方法是使用NumPy。
d = {'width' : [1,2,3,5,3,5,3],
'height' : [1,2,3,5,5,3],
'length' : [1,3,3,7,8,0,0,7,2,3,6,3,2,3],
'composition' : [1,2,3,5,5,3],
'year' : [7,5,3,2,1,6,4,9,11],
'efficiency' : [1,1,2,3,5,8,13,21,34]}
你需要一个你的名字的顺序:
names = ['width' ,'height', 'length' ,'composition', 'year','efficiency']
导入 NumPy:
import numpy as np
找到形状:
shape = tuple(len(d[name]) for name in names)
shape 是:
(7, 6, 14, 6, 9, 9)
创建一个零数组:
lookup = np.zeros(shape, dtype=np.uint16)
我使用非常小的无符号整数来节省空间。如果需要,您可以使用更大的数字:
现在lookup可以这样使用:
>>> lookup[0, 0, 0, 0, 0, 0]
0
>>> lookup[0, 0, 0, 0, 0, 0] = 12
>>> lookup[0, 0, 0, 0, 0, 0]
12
查找efficiency的所有值:
>>> lookup[0, 0, 0, 0, 0, :]
array([12, 0, 0, 0, 0, 0, 0, 0, 0], dtype=uint16)
year 和 efficiency 的所有值:
>>> lookup[0, 0, 0, 0, :, :]
array([[12, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint16)
有用的类
为方便起见,包装成一个类:
class Lookup(object):
def __init__(self, dims, dtype=np.uint16):
self.names = [item[0] for item in dims]
self.shape = [item[1] for item in dims]
self.repr = np.zeros(self.shape, dtype=dtype)
def _make_loc(self, coords):
return [coords.get(name, slice(None)) for name in self.names]
def get_value(self, coords):
return self.repr.__getitem__(self._make_loc(coords))
def set_value(self, coords, value):
return self.repr.__setitem__(self._make_loc(coords), value)
指定尺寸:
dims = [('width', 7),
('year', 9),
('composition', 6),
('height', 6),
('efficiency', 9),
('length', 14)]
创建一个实例:
lookup = Lookup(dims)
设置一个值:
coords1 = {'width': 3,
'height': 1,
'composition': 2,
'year': 6,
'length': 3}
lookup.set_value(coords1, 11)
取回一个值:
coords2 = {'width': 3,
'height': 1,
'composition': 2,
'year': 6}
lookup.get_value(coords2)
给你:
array([[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint16)