首页 > 解决方案 > Numpy:移动元组映射?

问题描述

假设我有一个名为 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'

首先,我需要构建一个窗口大小为 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映射到与目标dict对应的索引中,最终结果是这样的,

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

标签: pythonpython-3.xlistnumpynumpy-ndarray

解决方案


你离得太近了!对于列表理解,您需要从 3 中取出 3len而不是进行楼层划分,并添加您的步长:

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

要将这一点推广到所有步长和窗口大小:

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.


推荐阅读