如何使用python循环函数更改List中元素的顺序?

时间:2019-03-02 11:59:18

标签: python python-2.7

我有一个列表:

s=[[[’A’, ’B’], [’C’]],[[’A’], [’B’]], [[’B’], [’A’]]]

此列表的长度为3,这意味着我应该获得该列表的6个不同的顺序:

这意味着结果应该是

[[[’A’, ’B’], [’C’]],[[’A’], [’B’]], [[’B’], [’A’]]]
[[[’A’], [’B’]],[[’A’, ’B’], [’C’]], [[’B’], [’A’]]]
[[[’B’], [’A’]],[[’A’], [’B’]],[[’A’, ’B’], [’C’]]]
.....

我的代码是:

COUNT=0
order = []
def perm(n,begin,end):
    global COUNT
    if begin>=end:
       order.append(n)
       COUNT +=1
    else:
       i=begin
       for num in range(begin,end):
            n[num],n[i]=n[i],n[num]
            perm(n,begin+1,end)
            n[num],n[i]=n[i],n[num]
  return order
  F =  [[['A', 'B'], ['C']],[['A'], ['B']], [['B'], ['A']]]
  perm(F,0,len(F))

但是这个结果是错误的,它返回相同列表的六倍!

2 个答案:

答案 0 :(得分:0)

我无法确定您的代码出了什么问题,但是您可以使用标准库中的itertools模块来获得预期的结果:

import itertools

F =  [[['A', 'B'], ['C']],[['A'], ['B']], [['B'], ['A']]]
for item in itertools.permutations(F):
    print(item)

输出:

([['A', 'B'], ['C']], [['A'], ['B']], [['B'], ['A']])
([['A', 'B'], ['C']], [['B'], ['A']], [['A'], ['B']])
([['A'], ['B']], [['A', 'B'], ['C']], [['B'], ['A']])
([['A'], ['B']], [['B'], ['A']], [['A', 'B'], ['C']])
([['B'], ['A']], [['A', 'B'], ['C']], [['A'], ['B']])
([['B'], ['A']], [['A'], ['B']], [['A', 'B'], ['C']]) 

答案 1 :(得分:0)

您的问题是您尚未掌握如何复制列表列表。您仅将引用n添加到order列表中。引用指向数据-一旦更改数据,您创建的任何其他引用仍将指向同一数据。通过在perm上迭代调用n可以创建很多东西:

将代码更改为:

import copy 

COUNT=0
order = []
def perm(n,begin,end):
    global COUNT
    if begin>=end:
       order.append(copy.deepcopy(n))   # create a deep copy of the data n points to
       COUNT +=1                        # and store it so it does not change if you 
    else:                               # pass n to perm again further down the line
       i=begin
       for num in range(begin,end):
            n[num],n[i]=n[i],n[num]
            perm(n,begin+1,end)
            n[num],n[i]=n[i],n[num]
    return order


F =  [[['A', 'B'], ['C']],[['A'], ['B']], [['B'], ['A']]]
print(perm(F,0,len(F)))

输出:

[[[['A', 'B'], ['C']], [['A'], ['B']],[['B'], ['A']]], 
 [[['A', 'B'], ['C']], [['B'], ['A']], [['A'], ['B']]], 
 [[['A'], ['B']], [['A', 'B'], ['C']], [['B'], ['A']]], 
 [[['A'], ['B']], [['B'], ['A']], [['A', 'B'], ['C']]], 
 [[['B'], ['A']], [['A'], ['B']], [['A', 'B'], ['C']]], 
 [[['B'], ['A']], [['A', 'B'], ['C']], [['A'], ['B']]]]