python - 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
]
解决方案
你离得太近了!对于列表理解,您需要从 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
.
推荐阅读
- serialization - 处理 Arduino 通信比较
- python - 大规模约束二次规划?
- webpack - 如何知道 Webpack 的 4 个 splitChunks 是否有效?
- angular - 测试角度 i18n - 如何提供 i18nLocale 进行测试
- python - 从python中的json文件中提取元素
- matlab - 在冲浪图中重新缩放 x 轴
- excel - 使用 Visual Basic 在 Excel 中嵌入链接图片
- rxjs - 在继续 redux observable 之前等待第二个异步操作
- css - 使主容器使用 100% 的高度
- angular - 如何在联系表单的地址类数组中显示来自json的数据