按可变长度将列表扩展为列表列表

时间:2018-04-13 16:26:27

标签: python list

说我有一个清单

my_input_list = [22,33,56,1]

从变量target_len我想制作那个长度的(排他的,已排序的)子列表

target_len = 2
#my_output_list_not_sorted = [[22,33][22,56][22,1][33,56][33,1][56,1]]
my_output_list = [[22,33][22,56][1,22][33,56][1,33][1,56]]

target_len = 3
#my_output_list_not_sorted = [[[22,33,56][22,33,1][33,56,1]]
my_output_list = [[22,33,56][1,22,33][1,33,56]]

有没有一种巧妙的方法可以做到这一点?

如果需要,我可以先对my_input_list进行排序。

谢谢!

1 个答案:

答案 0 :(得分:2)

您似乎需要itertools.combinations

import itertools
my_input_list = [22,33,56,1]
target_len = 2
print([sorted(x) for x in itertools.combinations(my_input_list, target_len)])

<强>输出:

[[22, 33], [22, 56], [1, 22], [33, 56], [1, 33], [1, 56]]