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 itertoolsbinations(t_list, x + 1):print(i)
#取m = 2,允许重复的组合
print("combinations_with_replacement")
for i in itertoolsbinations_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标准库,简直事半功倍!
本文发布于:2024-01-30 15:59:08,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170660154921169.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |