Numpy:移动元组映射?

Numpy: moving tuple mapping?

假设我有一个名为 target 的元组列表,如下所示

import itertools
target = list(itertools.product(['a','b','c','d'], repeat = 4))
target = {target[i]: i for i in range(0, len(target))}
print(target)
{('a', 'a', 'a', 'a'): 0,
 ('a', 'a', 'a', 'b'): 1,
 ...
 ('d', 'd', 'd', 'c'): 254,
 ('d', 'd', 'd', 'd'): 255}

现在,如果我有下面的列表,

source = ['a','b','b','d','a','b','d','c','a','d','b','a','d','c','a'] # only contains 'a', 'b', 'c'

首先,我需要构造一个 windows 大小为 k 的移动元组列表,这里假设 k = 4,步长 d = 2,看起来像

[('a','b','b','d'),
('b','d','a','b'),
('a','b','d','c'),
('d','c','a','d'),
('a','d','b','a'),
('b','a','d','c'),
('d','c','a') # remove the last one if its len doest equals to k
]

我尝试使用列表理解,

movingTuple = [(source[i], source[i+1], source[i+2],source[i+3]) for i in range(len(source)//d)]

但是最后一个元素是错误的。我该如何修复这部分?

然后,我需要将movingTuple映射到目标字典对应的索引中,最终结果是这样的,

[
14,
20,
50,
87,
...
187
]

你们太亲密了!对于列表理解,您需要从 len 中减去 3 而不是进行楼层划分,并添加您的步长:

movingTuple = [(source[i], source[i+1], source[i+2],source[i+3]) for i in range(0,len(source)-3,2)]

将此概括为所有步骤和 window 尺寸:

window_size = 4
step_size = 2
movingTuple = [tuple(source[i+k] for k in range(window_size)) for i in range(0,len(source)-(window_size-1),step_size)]

并将每个值索引到目标中 dict:

result = [target[t] for t in movingTuple]

这种方法可能比尝试使用 NumPy 更快。