Sha*_*sky 5 python python-itertools
我们可以从Python 3中的itertools.product结果中获取特定索引中的元素吗?像下面这样:
xlist = itertools.product('abc', repeat=3)
element = xlist[10]
Run Code Online (Sandbox Code Playgroud)
在到达索引之前,您不必迭代生成器,但您可以立即生成该乘积,时间复杂度为 O(1),如此处所述。将其调整为以下(lst, repeat)形式:
def nth_product(lst, repeat, n):
k = len(lst)
return [lst[n // (k**r) % k] for r in range(repeat-1, -1, -1)]
Run Code Online (Sandbox Code Playgroud)
例子:
>>> lst = list(range(10))
>>> ref = list(itertools.product(lst, repeat=3))
>>> all(nth_product(lst, 3, i) == list(r) for i, r in enumerate(ref))
True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2039 次 |
| 最近记录: |