python例子itertools中的product()和permutations()

本文介绍如何使用Python的itertools库进行数字的全排列和笛卡尔积运算,通过具体示例展示了permutations和product函数的使用方法。

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

3.对数字进行全排列

使用itertools.permutations

from itertools import permutations

data_list = permutations([1,2,3,4],2)#对数字1,2,3,4,进行两两组合,等同于全排列
for data in data_list:
print(data)
结果

(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)

4.笛卡尔积

使用itertools.product
product返回两个序列的笛卡尔积,有两种使用方式

eg1.

from itertools import product

seq = product([1,2],repeat=3)

for i in seq:
print(i)
结果

(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 2, 2)
(2, 1, 1)
(2, 1, 2)
(2, 2, 1)
(2, 2, 2)
eg2.

from itertools import product

seq = product(‘123’,‘56’)

for i in seq:
print(i)
结果

(‘1’, ‘5’)
(‘1’, ‘6’)
(‘2’, ‘5’)
(‘2’, ‘6’)
(‘3’, ‘5’)
(‘3’, ‘6’)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值