Python 置换代码并不是我想要的那样

Python 置换代码并不是我想要的那样,python,permutation,combinations,Python,Permutation,Combinations,我对python非常陌生,我已经完成了这段代码,但并没有完全按照我的意愿去做。 非常感谢你的帮助 这是我到目前为止的代码 def permute(LIST): length=len(LIST) if length <= 1: yield LIST else: for n in range(0,length): for end in permute( LIST[:n] + LIST[n+1:] ):

我对python非常陌生,我已经完成了这段代码,但并没有完全按照我的意愿去做。 非常感谢你的帮助

这是我到目前为止的代码

def permute(LIST):

    length=len(LIST)
    if length <= 1:
        yield LIST
    else:
        for n in range(0,length):
             for end in permute( LIST[:n] + LIST[n+1:] ):
                 yield [ LIST[n] ] + end
我可以对代码做些什么来实现此更改

谢谢你的帮助


编辑:我无法使用ITERTOOLS确定。我使用itertools得到-1。排列:(

似乎您需要在不使用itertools的情况下进行重复排列。 给你:

def permutation_with_repitition(items, prefix):
  if len(prefix) == len(items):
     yield prefix

  else:
    for item in items:
      prefix.append(item)
      for p in  permutation_with_repitition(items, prefix):
        yield p
      prefix.pop()

L = [1,2,3]

for p in permutation_with_repitition(L, []):
  print p
输出:

[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 1]
[1, 2, 2]
[1, 2, 3]
[1, 3, 1]
[1, 3, 2]
[1, 3, 3]
[2, 1, 1]
[2, 1, 2]
[2, 1, 3]
[2, 2, 1]
[2, 2, 2]
[2, 2, 3]
[2, 3, 1]
[2, 3, 2]
[2, 3, 3]
[3, 1, 1]
[3, 1, 2]
[3, 1, 3]
[3, 2, 1]
[3, 2, 2]
[3, 2, 3]
[3, 3, 1]
[3, 3, 2]
[3, 3, 3]
但也许这就是你想要的:

>>> I = range(3)
>>> print list(itertools.product(I, repeat=len(I)))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]

恐怕你要的不是排列。还是检查我的答案吧。。
>>> I = range(3)
>>> print list(itertools.product(I, repeat=len(I)))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]