计算迭代工具的第n个结果。product() [英] Calculating the nth result for itertools.product()

查看:23
本文介绍了计算迭代工具的第n个结果。product()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算迭代工具的第n个结果。product()

test = list(product('01', repeat=3))
print(test)

desired_output = test[0]
print(desired_output)

所以不是得到:

[('0', '0', '0'), ('0', '0', '1'), ('0', '1', '0'), ('0', '1', '1'), ('1', '0', '0'), ('1', '0', '1'), ('1', '1', '0'), ('1', '1', '1')]

我正在尝试获取:

('0', '0', '0')

但是,正如您可能已经猜到的那样,它不能很好地伸缩。这就是我尝试只计算第n个值的原因。

我通读了 Nth Combination但我需要产品()提供的重复功能

提前谢谢!

推荐答案

repeat功能很容易模拟。这里是this博客文章中描述的Ruby代码的一个Python版本。

def product_nth(lists, num):
    res = []
    for a in lists:
        res.insert(0, a[num % len(a)])
        num //= len(a)

    return ''.join(res)

将此函数调用为

>>> repeats = 50
>>> chars = '01'
>>> product_nth([chars] * repeats, 12345673)
'00000000000000000000000000101111000110000101001001'

以下是它测试的一些时间:

repeat = 50
idx = 112345673

%timeit i = product_nth(['01'] * repeat, idx)
%%timeit
test = product('01', repeat=repeat)
one = islice(test, idx, idx+1)
j = ''.join(next(one))

2.01 s ± 22.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
36.5 µs ± 201 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

print(i == j)
True

另一个答案具有误导性,因为它歪曲了islice的功能。例如,请参阅:

def mygen(r):
    i = 0
    while i < r:
        print("Currently at", i)
        yield i
        i += 1

list(islice(mygen(1000), 10, 11))

# Currently at 0
# Currently at 1
# Currently at 2
# Currently at 3
# Currently at 4
# Currently at 5
# Currently at 6
# Currently at 7
# Currently at 8
# Currently at 9
# Currently at 10
# Out[1203]: [10]

islice将单步执行每一次迭代,在指定索引之前丢弃结果。对product的输出进行切片时也会发生同样的情况-该解决方案对大N无效。

这篇关于计算迭代工具的第n个结果。product()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆