[英]generating a full combination of values from multiple lists in python?
我想从多个列表中生成值组合的全矩阵。 但是我并不总是知道会提供多少个列表,每个列表的长度可以不同。 我可以通过滥用itertools.product()来获得答案,但是我认为这太过分了。 还有更Python化的方式吗?
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.