遍历 4 个数字的组合

jen*_*ice 3 python combinations

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

    import random
Run Code Online (Sandbox Code Playgroud)

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

array = ['1234', '1243', '1342', '1324' ect]
Run Code Online (Sandbox Code Playgroud)


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

Rom*_*est 7

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

import itertools

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

print(a)   # prints 24 permutations
Run Code Online (Sandbox Code Playgroud)

输出:

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