繁体   English   中英

Python itertools.product()获取项索引

[英]Python itertools.product() get item index

我有一个给定的元组my_tuple ,我知道它在itertools.product()的返回对象中。 如何在不迭代itertools.product()对象的情况下找到my_tuple的索引?

import itertools
permutations = itertools.product(my_sorted_list, repeat = perm_length)

预期输出类似于any_list.index(interesting_pattern)

编辑请注意,由于内存限制,我无法在对象上使用list()

使用Python 2.7

在这种情况下,您不想使用itertools.product 如果你只想要索引,那么你应该用数学来计算它。

像其他人之前所说的那样,这个很慢,需要大量的记忆:

import itertools
print list(itertools.product([0, 2, 3, 5], repeat=3)).index((3, 0, 2))

更好的是:

def product_index(sorted_list, repeat, interesting_pattern):
    result = 0
    for index, number in enumerate(interesting_pattern):
        result += sorted_list.index(number) * len(sorted_list)**(repeat - 1 - index)
    return result

print product_index([0, 2, 3, 5], 3, (3, 0, 2))

说明:

只需查看list(itertools([0, 2, 3, 5], repeat=3))的输出list(itertools([0, 2, 3, 5], repeat=3))

[(0, 0, 0), (0, 0, 2), (0, 0, 3), (0, 0, 5), (0, 2, 0), (0, 2, 2), (0, 2, 3), 
 (0, 2, 5), (0, 3, 0), (0, 3, 2), (0, 3, 3), (0, 3, 5), (0, 5, 0), (0, 5, 2), 
 (0, 5, 3), (0, 5, 5), (2, 0, 0), (2, 0, 2), (2, 0, 3), (2, 0, 5), (2, 2, 0), 
 (2, 2, 2), (2, 2, 3), (2, 2, 5), (2, 3, 0), (2, 3, 2), (2, 3, 3), (2, 3, 5), 
 (2, 5, 0), (2, 5, 2), (2, 5, 3), (2, 5, 5), (3, 0, 0), (3, 0, 2), (3, 0, 3), 
 (3, 0, 5), (3, 2, 0), (3, 2, 2), (3, 2, 3), (3, 2, 5), ...]

由于输入列表已排序,因此生成的元组也会排序。 首先, itertools.product生成长度为3所有元组,以0开头。 然后有所有长度为3元组以2开头。 等等。

因此,算法遍历interesting_pattern每个元素,并确定这些元组中有多少以较小的数字开头。

因此,对于interesting_pattern = (3, 0, 2)我们有:

  • 有多少长度为3元组,第一个元素小于3 对于第一个元素,有2种可能性( 02 ),所有其他元素可以是一切(4种可能性)。 所以有2*4*4 = 2*4^2 = 32 现在我们有第一个数字3,只需要查看子数字(0, 2)
  • 有多少长度为2元组,第一个元素小于0 第一个元素不可能,但第二个元素有4种可能性,因此0*4 = 0*4^1 = 0

  • 最后。 有多少长度为1元组,第一个元素小于2 第一个元素( 0 )有1种可能性,因此1 = 1*4^0 = 1

总共得到32 + 0 + 1 = 33 该指数是33

编辑:

此算法可能更快,因为您不必计算任何功率。

def product_index2(sorted_list, interesting_pattern):
    result = 0
    for number in interesting_pattern:
        result = result * len(sorted_list) + sorted_list.index(number)
    return result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM