说我有一个清单
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进行排序。
谢谢!
答案 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]]