python中有个标准库itertools就是专门用来解决各种排序,组合问题的,例子如下:
代码:
import itertools
#从n个数中取出m个数,并将其列表打印出来
t_list = ["1", "2", "3", "4", "5"]
#随机取两个数,允许重复
print("product")
for i in itertools.product(t_list, repeat=2):
print(i)
#取3个数的排列
print("permutations")
for i in itertools.permutations(t_list, 3):
print(i)
#取n= 5,分别取m = 1,2,3,4,5的组合
print("combinations")
for x in range(len(t_list)):
for i in itertools.combinations(t_list, x + 1):
print(i)
#取m = 2,允许重复的组合
print("combinations_with_replacement")
for i in itertools.combinations_with_replacement(t_list, 2):
print(i)
输出如下:
product
('1', '1')
('1', '2')
('1', '3')
('1', '4')
('1', '5')
('2', '1')
('2', '2')
('2', '3')
('2', '4')
('2', '5')
('3', '1')
('3', '2')
('3', '3')
('3', '4')
('3', '5')
('4', '1')
('4', '2')
('4', '3')
('4', '4')
('4', '5')
('5', '1')
('5', '2')
('5', '3')
('5', '4')
('5', '5')
permutations
('1', '2', '3')
('1', '2', '4')
('1', '2', '5')
('1', '3', '2')
('1', '3', '4')
('1', '3', '5')
('1', '4', '2')
('1', '4', '3')
('1', '4', '5')
('1', '5', '2')
('1', '5', '3')
('1', '5', '4')
('2', '1', '3')
('2', '1', '4')
('2', '1', '5')
('2', '3', '1')
('2', '3', '4')
('2', '3', '5')
('2', '4', '1')
('2', '4', '3')
('2', '4', '5')
('2', '5', '1')
('2', '5', '3')
('2', '5', '4')
('3', '1', '2')
('3', '1', '4')
('3', '1', '5')
('3', '2', '1')
('3', '2', '4')
('3', '2', '5')
('3', '4', '1')
('3', '4', '2')
('3', '4', '5')
('3', '5', '1')
('3', '5', '2')
('3', '5', '4')
('4', '1', '2')
('4', '1', '3')
('4', '1', '5')
('4', '2', '1')
('4', '2', '3')
('4', '2', '5')
('4', '3', '1')
('4', '3', '2')
('4', '3', '5')
('4', '5', '1')
('4', '5', '2')
('4', '5', '3')
('5', '1', '2')
('5', '1', '3')
('5', '1', '4')
('5', '2', '1')
('5', '2', '3')
('5', '2', '4')
('5', '3', '1')
('5', '3', '2')
('5', '3', '4')
('5', '4', '1')
('5', '4', '2')
('5', '4', '3')
combinations
('1',)
('2',)
('3',)
('4',)
('5',)
('1', '2')
('1', '3')
('1', '4')
('1', '5')
('2', '3')
('2', '4')
('2', '5')
('3', '4')
('3', '5')
('4', '5')
('1', '2', '3')
('1', '2', '4')
('1', '2', '5')
('1', '3', '4')
('1', '3', '5')
('1', '4', '5')
('2', '3', '4')
('2', '3', '5')
('2', '4', '5')
('3', '4', '5')
('1', '2', '3', '4')
('1', '2', '3', '5')
('1', '2', '4', '5')
('1', '3', '4', '5')
('2', '3', '4', '5')
('1', '2', '3', '4', '5')
combinations_with_replacement
('1', '1')
('1', '2')
('1', '3')
('1', '4')
('1', '5')
('2', '2')
('2', '3')
('2', '4')
('2', '5')
('3', '3')
('3', '4')
('3', '5')
('4', '4')
('4', '5')
('5', '5')
用了python标准库,简直事半功倍!