运行 通过 4 个数字的组合

Running through combinations of 4 numbers

我需要一个代码 运行 通过 4 个数字的可能组合,例如 1234 将产生 1234、1243、1324 ...等的 24 种组合。但不做 ['1', '12', '123', ect] 我希望它只有 4 个数字长度组合,(只是改变顺序)
一个长期的选择是

    import random

随机化 4 个数字中的一个,随机化一个又一个,检查该组合是否已被打印或添加到包含可能组合的数组中,然后最终打印出所有这些组合。

array = ['1234', '1243', '1342', '1324' ect]


这会花费很长时间,而且效率非常低。 对编码很陌生:) 谢谢

使用itertools.permutations() and str.join()函数的解决方案:

import itertools

n = '1234'
a = [''.join(i) for i in itertools.permutations(n, 4)]

print(a)   # prints 24 permutations

输出:

['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']

您可以在python中使用内置模块itertools。参考这个已经问过的问题here

import itertools
array = itertools.permutations([1, 2, 3, 4])

for eachpermutation in array:
    print(eachpermutation )

应该给你这样的输出

(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, 3, 4, 1)
(2, 4, 1, 3)
(2, 4, 3, 1)
(3, 1, 2, 4)
(3, 1, 4, 2)
(3, 2, 1, 4)
(3, 2, 4, 1)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 1, 3, 2)
(4, 2, 1, 3)
(4, 2, 3, 1)
(4, 3, 1, 2)
(4, 3, 2, 1)

如果您需要将子列表连接成一个数字,您可以使用提供的答案 here

for eachpermutation in array:
    print(int(''.join(str(i) for i in eachpermutation )))

为您提供以下输出

1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321

希望对您有所帮助