Python 中没有逆序的排列

Permutations without reversed sequences in Python

我想生成一个包含 4 位数字所有排列的列表,其中:

我想知道:

import itertools
inp_list = range(1, 5)

# 1. Create the list of all permutations.
permutations = list(itertools.permutations(inp_list))

# 2. Remove sequences that are the reverse of another.
for _p in permutations[::-1]:
    if _p[::-1] in permutations:
        permutations.remove(_p)

for _p in permutations:
    print("\t".join(map(str, _p)))

要简化您的代码并使其更高效,您可以:

1- 使用 python set 作为容器(检查元素是否存在要快得多)

2-直接添加最终输出

3- 避免使用排列创建临时列表,将其保留为生成器

from itertools import permutations
inp_list = range(1, 5)

out = set()
for p in permutations(inp_list): # loop over generator output
    p = '\t'.join(map(str,p))    # craft the desired output format
    if not p[::-1] in out:       # is the reverse not already in the set?
        out.add(p)               # then add the item
        print(p)                 # and print it

输出:

1   2   3   4
1   2   4   3
1   3   2   4
1   3   4   2
1   4   2   3
1   4   3   2
2   1   3   4
2   1   4   3
2   3   1   4
2   4   1   3
3   1   2   4
3   2   1   4

您可以只使用每个反转对中较小的一对:

from itertools import permutations

for p in permutations(range(1, 5)):
    if p < p[::-1]:
        print(*p)

输出:

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 4 1 3
3 1 2 4
3 2 1 4