2 回答
TA贡献1906条经验 获得超3个赞
你可以用itertools.product
那个
计算输入可迭代对象的笛卡尔积。
final_list = list(itertools.product(*level_list)))
例子
list(itertools.product(*[[1, 2], [3, 4]]))) # [(1, 3), (1, 4), (2, 3), (2, 4)]
TA贡献1801条经验 获得超8个赞
level_list = [
[1, 2, 3],
[1, 2],
[1, 2, 3, 4, 5]
]
nb_lists = len(level_list)
least_significant_position = nb_lists - 1
indices = defaultdict(int)
solution_found = False
solution = list()
while not solution_found:
possible_combination = list()
index_incremented = False
for i in range(nb_lists, 0, -1):
current_selection = level_list[i - 1]
index = indices[i - 1]
possible_combination.insert(0, current_selection[index])
max_index_for_this_list = len(current_selection) - 1
if not index_incremented and index < max_index_for_this_list:
indices[i - 1] += 1
index_incremented = True
if i - 1 != least_significant_position:
less_significant_position = i
while less_significant_position <= least_significant_position:
indices[less_significant_position] = 0
less_significant_position += 1
solution.append(possible_combination)
if not index_incremented:
solution_found = True
print(solution.__str__())
添加回答
举报