【发布时间】:2021-08-05 16:19:33
【问题描述】:
假设我有一个名为 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
]
【问题讨论】:
标签: python python-3.x list numpy numpy-ndarray