简体   繁体   中英

Cleaner way to do itertools product combination in Python?

I have the following sample code. I'm prepending a mandatory '1' in front of the generated products. Is there a better way to do it using list generation without using tuple([1]) + a ?

from itertools import product

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

The output is:

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

Also, what's the best way to get the following result from the above output (Basically, multiplying each value in the tuple by 10^i where i is in respective index and summing that result):

[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()]

Will this work for you? BTW works for different values of repeat parameter.

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

I'd first create a helper function to handle the numeric joining.

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

Then just use that in a simplified version of your list comprehension

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

The technique I use to transform a tuple of digits into a number is to simply cast each digit to a string so I can use ordinary string joining, then cast it back into an int. I also remove the redundant list , which is not necessary when we're iterating over the result of product anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM