Python组合和排列代码

时间:2014-09-10 00:46:30

标签: python combinations itertools

我有以下代码来生成组合集,将组合附加到列表中,并返回列表。

def make_combination():
  import itertools  
  max_range = 5 
  indexes = combinations_plus = []
  for i in range(0, max_range): 
    indexes.append(i)
    for i in xrange(2, max_range): 
      each_combination = [list(x) for x in itertools.combinations(indexes, i)]
      combinations_plus.append(each_combination)
  retrun combinations_plus

它产生了许多我不想要的组合(很难显示)。但是,我想要以下组合:

1)[[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2] ,3],[2,4],[3,4]]

2)[[0,1,2],[0,1,3],[0,1,4],[0,2,3],[0,2,4],[0,3] ,4],[1,2,3],[1,2,4],[1,3,4],[2,3,4]]

3)[[0,1,2,3],[0,1,2,4],[0,1,3,4],[0,2,3,4],[1,2] ,3,4]]

我认为问题在以下几行,但我不知道它是什么。任何关于错误是什么的想法。

combinations_plus.append(each_combination)

2 个答案:

答案 0 :(得分:1)

执行所需操作的更简单方法如下:

list(list(itertools.combinations(list(range(5)), i)) for i in range(2, 5))

答案 1 :(得分:0)

要修复原始代码,有两个问题:

indexes = combinations_plus = []

上面为完全相同的列表创建了两个名称。附加到两者都附加到你想要的不是。

两个for语句不应该嵌套,或者索引列表不完整:

for i in range(0, max_range): 
    indexes.append(i)
for i in xrange(2, max_range): 
    each_combination = [list(x) for x in itertools.combinations(indexes, i)]
    combinations_plus.append(each_combination)

事实上,使用indexes初始化range并跳过第一个for循环:

indexes = range(max_range) # becomes [0,1,2,3,4]
combinations_plus = []

通过这些修复(并修复return的拼写,您有:

def make_combination():
  import itertools  
  max_range = 5 
  indexes = range(max_range)
  combinations_plus = []
  for i in xrange(2, max_range): 
    each_combination = [list(x) for x in itertools.combinations(indexes, i)]
    combinations_plus.append(each_combination)
  return combinations_plus

返回(为了可读性添加了换行符):

[[[0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]],
 [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]],
 [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [1, 2, 3, 4]]]