Python 如何通过从唯一列表中最多选取n项来查找所有组合
假设我有一个独特的列表:Python 如何通过从唯一列表中最多选取n项来查找所有组合,python,list,Python,List,假设我有一个独特的列表: H_coordinates = [(0, 1), (0, 3), (1, 0), (1, 2), (2, 1), (2, 2)] 以及一个变量,该变量表示列表中我最多要的项数: num_of_H = 2 我试过: all_H_combinations = itertools.combinations(H_coordinates, num_of_H) 但当我打印时: print('all_H_combinations:', all_H_combinations )
H_coordinates = [(0, 1), (0, 3), (1, 0), (1, 2), (2, 1), (2, 2)]
以及一个变量,该变量表示列表中我最多要的项数:
num_of_H = 2
我试过:
all_H_combinations = itertools.combinations(H_coordinates, num_of_H)
但当我打印时:
print('all_H_combinations:', all_H_combinations )
我得到:
all_H_combinations: <itertools.combinations object at 0x0000021C1B4A5AE8>
所有组合:
我做错了什么?或者有其他方法吗?这是正确的:
itertools.combines
返回一个生成器-您需要循环它以查看它生成了什么
或者将其转换为列表(如果有很多组合,则可能需要大量时间和内存):
只是:
输出:
all_H_combinations: [((0, 1), (0, 3)), ((0, 1), (1, 0)), ((0, 1), (1, 2)), ((0, 1), (2, 1)), ((0, 1), (2, 2)), ((0, 3), (1, 0)), ((0, 3), (1, 2)), ((0, 3), (2, 1)), ((0, 3), (2, 2)), ((1, 0), (1, 2)), ((1, 0), (2, 1)), ((1, 0), (2, 2)), ((1, 2), (2, 1)), ((1, 2), (2, 2)), ((2, 1), (2, 2))]
print('all_H_combinations:', [p for p in all_H_combinations])
all_H_combinations: [((0, 1), (0, 3)), ((0, 1), (1, 0)), ((0, 1), (1, 2)), ((0, 1), (2, 1)), ((0, 1), (2, 2)), ((0, 3), (1, 0)), ((0, 3), (1, 2)), ((0, 3), (2, 1)), ((0, 3), (2, 2)), ((1, 0), (1, 2)), ((1, 0), (2, 1)), ((1, 0), (2, 2)), ((1, 2), (2, 1)), ((1, 2), (2, 2)), ((2, 1), (2, 2))]