gpt4 book ai didi

在 python 2.4 中模拟 itertools.product 的 Pythonic 方法

转载 作者:太空宇宙 更新时间:2023-11-03 12:34:42 24 4
gpt4 key购买 nike

我有一个使用 itertools.product 的 python 3 脚本,但我需要能够在只安装了 python 2.4 的机器上运行它。由于 itertools.product 是 python 2.6 中的新功能,我无法再使用此功能。

如何在 Python 2.4 中以 pythonic 方式模拟 itertools.product

最佳答案

来自 http://docs.python.org/library/itertools.html#itertools.product 的等效代码

def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)

关于在 python 2.4 中模拟 itertools.product 的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7732141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com