Python 中列表元素的排列

Dba*_*att 1 python list python-itertools

我有一个清单A。我想要特定的排列,以便列表中同一元素不会多次占用同一位置。我介绍当前和预期的产出。我还希望代码适用于任何长度的A.

from itertools import permutations

A = [1, 2, 3]

# Generate all possible permutations and convert tuples to lists
all_permutations = [list(perm) for perm in permutations(A)]

# Print the permutations
for perm in all_permutations:
    print(perm)
Run Code Online (Sandbox Code Playgroud)

当前输出为

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
Run Code Online (Sandbox Code Playgroud)

预期输出是

[1,2,3]
[3,1,2]
[2,3,1]
Run Code Online (Sandbox Code Playgroud)

Car*_*ten 6

i看起来您想按的所有可能值的元素旋转列表i。尝试这样的事情:

A = [1, 2, 3]

def rotate(a, i):
    return a[i:] + a[:i]

all_rotations = [rotate(A, i) for i in range(len(A))]

# Print the permutations
for r in all_rotations:
    print(r)
Run Code Online (Sandbox Code Playgroud)

输出是

[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
Run Code Online (Sandbox Code Playgroud)

如果您想要问题 ( [1,2,3], [3,1,2], [2,3,1]) 中的精确输出,只需旋转而-i不是i