我想用ID替换sequence
的所有项,这些ID告诉它们在哪个标签列表中。假设所有值在sequence
和labeller
中都是不同的,并且labeller
列表的并集具有与sequence
相同的项lsizes
对应于labeller
中列表的大小,对于Pythonic解决方案是多余的,但对于完全向量化的解决方案可能是必需的
sequence = [1, 2, 10, 5, 6, 4, 3, 8, 7, 9],
labeller = [[1, 2, 10], [3, 4, 5, 6, 7], [8, 9]]
lsizes = [3, 5, 2]
我知道如何用一种简单的方法解决它:
idx = {u:i for i, label in enumerate(labeller) for u in label}
tags = [idx[u] for u in sequence]
输出为:
tags = [0, 0, 0, 1, 1, 1, 1, 2, 1, 2]
在那之后,我把我所有的努力都用矢量化的方式来做。这对我来说相当复杂。这是我的尝试,只是猜测而已,但不幸的是,它没有通过我所有的测试。我希望我很接近:
sequence = np.array(sequence)
cl = np.concatenate(labeller)
_, cl_idx = np.unique(cl, return_index=True)
_, idx = np.unique(sequence[cl_idx], return_index=True)
tags = np.repeat(np.arange(len(lsizes)), lsizes)[idx]
#output: [0 0 1 1 0 1 1 1 2 2]
我怎样才能完成它?我也希望看到严谨的解释,它做什么以及如何更好地理解它。也欢迎任何来源
方法#1
对于那些追溯问题,^{} 似乎是一种方法,在这里也可以使用,重新使用
cl
-对
l
使用lsizes
使其完全矢量化。但是,我怀疑连接步骤可能很繁重。这是否值得,在很大程度上取决于子阵列的长度方法#2
对于正数,这里有一个数组索引作为散列机制-
备选方案:
相关问题 更多 >
编程相关推荐