为了账号安全,请及时绑定邮箱和手机立即绑定

如何找到特定范围内的所有整数集?

如何找到特定范围内的所有整数集?

慕盖茨4494581 2023-09-05 15:29:47
我有一个列表列表,我想找到列表中项目的所有排列。我很难解释这一点,所以这里有一个例子。我有三个清单:level_list = [    [1, 2, 3],    [1, 2],    [1, 2, 3, 4, 5]]我想最终得到一个列表列表,所有列表的长度都是 3,并且包含我原来的 3 个列表中的潜在选项;像这样:final_list =[    [1, 1, 1],    [1, 1, 2],    [1, 1, 3],    [1, 1, 4],    [1, 1, 5],    [1, 2, 1],    [1, 2, 2],    [1, 2, 3],    [1, 2, 4],    [1, 2, 5],    [2, 1, 1],    [2, 1, 2],    [2, 1, 3],    [2, 1, 4],    [2, 1, 5],    [2, 2, 1],    [2, 2, 2],    [2, 2, 3],    [2, 2, 4],    [2, 2, 5],    [3, 1, 1],    [3, 1, 2],    [3, 1, 3],    [3, 1, 4],    [3, 1, 5],    [3, 2, 1],    [3, 2, 2],    [3, 2, 3],    [3, 2, 4],    [3, 2, 5]]感觉如果我要手动执行此操作,我应该做我会做的事情,即:增加最后一个子列表,将其他两个常量的值保持为 1增加中间子列表,将第一个子列表的值保持为 1 并继续改变最终子列表完成第一个子列表如果我对列表的 # 进行硬编码,我可以使用嵌套的 for 循环来做到这一点,但这感觉非常“非 python 风格”,而且也不是真正可行,因为我最终需要它成为一个可以与任意数量的子列表一起使用的函数:final_list = []for i1 in level_list[0]:    for i2 in level_list[1]:        for i3 in level_list[2]:            final_list.append([i1, i2, i3])            print(final_list)这几乎就像我需要一个 for 循环嵌套的 for 循环。或者一些比我想象的更聪明的解决方案。我也愿意接受只接受最小值和最大值的解决方案——这将始终是整数列表,它们之间的步长为 1。
查看完整描述

2 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

你可以用itertools.product那个

计算输入可迭代对象的笛卡尔积。

final_list = list(itertools.product(*level_list)))

例子

list(itertools.product(*[[1, 2], [3, 4]]))) # [(1, 3), (1, 4), (2, 3), (2, 4)]


查看完整回答
反对 回复 2023-09-05
?
蝴蝶刀刀

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__())


查看完整回答
反对 回复 2023-09-05
  • 2 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信