从 python 中的多个列表生成值的完整组合?
generating a full combination of values from multiple lists in python?
我想从多个列表中生成值组合的完整矩阵。但是我并不总是知道会提供多少个列表,而且每个列表的长度都不同。我能够通过滥用 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)
result = list(itertools.product(*listoflists))
如果希望result
列表的元素类型为list
,则转换为:
result = [list(item) for item in result]
我想从多个列表中生成值组合的完整矩阵。但是我并不总是知道会提供多少个列表,而且每个列表的长度都不同。我能够通过滥用 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)
result = list(itertools.product(*listoflists))
如果希望result
列表的元素类型为list
,则转换为:
result = [list(item) for item in result]