python实现从n个数中取出m个数,并将其列表打印出来

本文介绍了Python标准库itertools的功能及用法,通过实例演示了如何使用itertools进行不同类型的组合和排列,包括产品组合、排列组合、组合以及允许重复的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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标准库,简直事半功倍!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值