无嵌套列表全排列
import itertools
a = [1,2,3]
b = list(itertools.permutations(a, len(a)))
print(b)
#结果:[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
len(a)是a列表的长度,这个是参数是可变的只要>=0且<=len(a)即可
import itertools
a = [1,2,3]
b = list(itertools.permutations(a, 2))
print(b)
#结果:[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
或者还可以这样实现全排列
from itertools import permutations
a = [1,2,3]
print(list(permutations(a)))
#结果:[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
字符串全排列
将字符串转为列表先
import itertools
str1 = "123"
a = list(str1)
list1 = []
b = list(itertools.permutations(a, len(str1)))
for i in b:
list1.append("".join(i))
print(b)
print(list1)
#结果:[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
#结果:['123', '132', '213', '231', '312', '321']
嵌套列表全排列
from itertools import product
a = [[1, 3, 11], [2, 4, 6], [7, 8, 9]]
b = list(product(*a))
print(b)
#结果:[(1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (3, 2, 7), (3, 2, 8), (3, 2, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9), (11, 2, 7), (11, 2, 8), (11, 2, 9), (11, 4, 7), (11, 4, 8), (11, 4, 9), (11, 6, 7), (11, 6, 8), (11, 6, 9)]
组合
import itertools
a = list(itertools.combinations([1, 2, 3, 4], 3))
print(a)
#结果:[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
import itertools
a = list(itertools.combinations([1, 2, 3, 4], 2))
print(a)
#结果:[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]