python - itertools.product - 返回列表而不是元组

标签 python python-itertools

我希望 itertools.product 返回一个列表而不是一个元组。我目前正在通过创建自己的函数来做到这一点:

def product_list(*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 list(prod)  # Yields list() instead of tuple()

代码来自 Python 文档 - 我只是修改了最后一行。这工作正常,但似乎不是很聪明。

还有哪些其他方法可以做到这一点?我正在考虑使用类似 decorator 的东西,或者用我自己的生成器函数包装它。我对这两个概念都不太熟悉,所以如果有人能告诉我,我将不胜感激。

编辑 我正在做这样的乱七八糟的事情:

for r0 in product_list([0, 1], repeat=3):
    r0.insert(0, 0)
    for r1 in product_list([0, 1], repeat=3):
        r1.insert(1, 0)
        for r2 in product_list([0, 1], repeat=3):
            r2.insert(2, 0)
            for r3 in product_list([0, 1], repeat=3):
                r3.insert(3, 0)

所以我更希望我的函数返回一个列表,而不是每次都强制转换它。 (我知道代码很乱,需要递归,但我稍后会考虑。我更感兴趣的是学习如何做我上面描述的事情)

最佳答案

itertools.product 是一个生成器,您可以轻松地将多个生成器链接在一起。下面是一个生成器表达式,它将 product 生成的每个元组更改为一个列表:

(list(tup) for tup in itertools.product(iterable1, iterable2, etc))

在您的示例代码中,您可以使用生成器表达式,或者您可以使用不同的方法将额外的值添加到您的值的前面,同时将它们保持为元组:

for r0 in itertools.product([0, 1], repeat=3):
    r0 = (0,) + r0 # keep r0 a tuple!
    for r1 in itertools.product([0, 1], repeat=3):
        r1 = (1,) + r1 # same here
        # ...

由于您没有显示您将 rN 变量用于什么目的,因此无法就最佳方法给出明确的答案。 (你对变量进行了编号有点代码味道。)事实上,由于你的循环只是计算另外三个 01 数字,你可能能够一次 product 调用就可以摆脱困境,它会一次性生成 n 个不同 r 值的列表:

for bits in itertools.product([0, 1], repeat=3*n):
    rs = [(i,) + bits[3*i:3*i+3] for i in range(n)]
    # do something with the list of r tuples here

关于python - itertools.product - 返回列表而不是元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22883348/

相关文章:

python - 使用 scrapy 抓取特定网站时出现 "Too many requests"错误

python - “int”对象不可下标 - 不知道如何修复

python - 在 Python 中将数字更改为字母

带有过滤器用法的python itertools groupby

python - 字典理解索引错误

python - 用于在 python 中查找替换列表的 itertools 或 functools

python - itertools tee() 迭代器分割

python - Matplotlib 的非线性颜色图

python - 试图在 Python 的字符串的特定部分中查找所有唯一值

python - 哪个 itertools 生成器不会跳过任何组合?