在 Python 中进行 itertools 产品组合的更简洁方法?

Cleaner way to do itertools product combination in Python?

我有以下示例代码。我在生成的产品前面添加了一个强制性的“1”。有没有更好的方法来使用列表生成而不使用 tuple([1]) + a?

from itertools import product

print [tuple([1]) + a for a in list(product([0, 1], repeat=2))]

输出为:

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

另外,从上面的输出中得到以下结果的最佳方法是什么(基本上,将元组中的每个值乘以 10^i,其中 i 在各自的索引中,并对结果求和) :

[100, 101, 110, 111]

tuple([1]) 等同于 (1,),您不需要调用 list:

print [(1,) + a for a in product([0, 1], repeat=2)]
def rawProducts(repeat=2):
  return product([0, 1], repeat=repeat)

def toNumber(seq):
  # here's the trick: the last parameter to reduce() is the initial value;
  # we pretend that we already have a 1 before we started iterating 
  # over seq, instead of prepending the 1 to seq.
  return reduce(lambda acc, x: 10 * acc + x, seq, 1)

result = [toNumber(prod) for prod in rawProducts()]

这对你有用吗?顺便说一句适用于 repeat 参数的不同值。

我首先创建一个辅助函数来处理数字连接。

def num_join(*digits):
    return int(''.join(map(str, digits)))

然后只需在列表理解的简化版本中使用它

print [num_join(1, *a) for a in product((0, 1), repeat=2)]

我用来将数字元组转换为数字的技术是简单地将每个数字转换为字符串,这样我就可以使用普通的字符串连接,然后将其转换回 int。我还删除了多余的 list,这在我们迭代 product 的结果时是不必要的。

map(int,("".join(("1",)+x) for x in list(product("01", repeat=2))))