【发布时间】:2017-10-19 14:05:00
【问题描述】:
我有一个问题,我需要识别在索引位置找到的元素 the Cartesian product of a series of lists 也是相反的,即从一系列列表中的元素的唯一组合中识别索引位置。
我编写了以下代码,可以很好地完成任务:
import numpy as np
def index_from_combination(meta_list_shape, index_combination ):
list_product = np.prod(meta_list_shape)
m_factor = np.cumprod([[l] for e,l in enumerate([1]+meta_list_shape)])[0:len(meta_list_shape)]
return np.sum((index_combination)*m_factor,axis=None)
def combination_at_index(meta_list_shape, index ):
il = len(meta_list_shape)-1
list_product = np.prod(meta_list_shape)
assert index < list_product
m_factor = np.cumprod([[l] for e,l in enumerate([1]+meta_list_shape)])[0:len(meta_list_shape)][::-1]
idxl = []
for e,m in enumerate(m_factor):
if m<=index:
idxl.append((index//m))
index = (index%m)
else:
idxl.append(0)
return idxl[::-1]
例如
index_from_combination([3,2],[2,1])
>> 5
combination_at_index([3,2],5)
>> [2,1]
[3,2] 描述了一系列两个列表,一个包含 3 个元素,另一个包含 2 个元素。组合[2,1] 表示由第一个列表中的第三个元素(零索引)和第二个列表中的第二个元素(同样是零索引)组成的排列。
...如果有点笨拙(并且,为了节省空间,忽略列表的实际内容,而是使用其他地方使用的索引从这些列表中获取内容 - 这在这里并不重要)。
注意重要的是我的功能相互镜像,这样:
F(a)==b and G(b)==a
即它们是彼此的倒数。
从链接的问题中,事实证明我可以用单线替换第二个函数:
list(itertools.product(['A','B','C'],['P','Q','R'],['X','Y']))[index]
这将返回提供的索引整数的唯一值组合(尽管在我心中有一些问号,即该列表中有多少是在内存中实例化的 - 但同样,这现在不一定重要)。
我要问的是,itertools 似乎是在考虑这些类型的问题的情况下构建的 - 是否存在与 itertools.product 函数同样简洁的逆向函数,给定一个组合,例如['A','Q','Y'] 将返回一个整数,描述该组合在笛卡尔积中的位置,这样如果将该整数输入itertools.product 函数将返回原始组合?
【问题讨论】: