从python中的多个列表生成值的完整组合?

时间:2015-10-30 13:47:43

标签: python generator

我想从多个列表生成一个完整的值组合矩阵。但我并不总是知道将提供多少列表,每个列表可以有不同的长度。我能够通过滥用itertools.product()得到答案,但我认为这太过分了。有更多的pythonic方式吗?

import itertools

listoflists = [
   ["happy","sad"],
   ["car","bike","truck"],
   ["true","false"],
   [3,6,34,8,31]]

def comboGenerator(lol):

  # create a uniform N-dimensional struct, big enough to hold longest dimension
  longest = max(map(lambda x: len(x),lol))
  superstruct = itertools.product(range(longest), repeat=len(lol))

  # visit each cell in the struct, ignore the empty ones
  for a in superstruct:
    combo = []
    try:
      for index in range(len(lol)):
        combo.append(lol[index][a[index]])
      yield (combo)
    except IndexError:  #this was an empty cell; try again
      pass

for x in comboGenerator(listoflists):
  print (x)

1 个答案:

答案 0 :(得分:1)

result = list(itertools.product(*listoflists))

如果您希望result列表的元素类型为list,请将其转换为:

result = [list(item) for item in result]