• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

深入认识Python中的itertools模块

python 搞代码 4年前 (2022-01-09) 30次浏览 已收录 0个评论
文章目录[隐藏]

Python视频教程栏目介绍itertools模块。

在Python中有一个功能强大的迭代工具包itertools,是Python自带的标准工具包之一。

product

由于itertools是内置库,不需要任何安装,直接import itertools即可。

product 用于求多个可迭代对象的笛卡尔积(Cartesian Product),它跟嵌套的 for 循环等价.即:

笛卡尔乘积是指在数学中,两个集合X和Y的笛卡尔积(Cartesian product),又称直积,表示为X × Y

product(A, B)和 “((x,y) for x in A for y in B)`一样.

import itertools
for item in itertools.product([1,2,3],[100,200]):
    print(item)
    
    
# 输出如下
(1, 100)
(1, 200)
(2, 100)
(2, 200)
(3, 100)
(3, 200)复制代码

permutations

通俗地讲,permutations就是返回可迭代对象的所有数学或者字符的全排列方式。

全排列,即产生指定数目的元素的所有排列(顺序有关),也就是高中排列组合中的那个A

permutations它接受一个集合对象,然后产生一个元组序列。

比如print(list(itertools.permutations('abc',3))),共有A33=6A_3^3=6A33=6种情况。

items = ['a','b','c']
from<i style="color:transparent">本文来源gaodai$ma#com搞$$代**码)网8</i> itertools import permutations
for i in permutations(items):
    print(i) #排列组合

print(list(itertools.permutations('abc',3))) 
# 输出如下
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]复制代码

如果需要指定长度的所有排列,可以传递一个可选的长度参数r

items = ['a','b','c']
from itertools import permutations
for i in permutations(items,2):
    print(i) #排列组合
    
# 输出如下
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')复制代码

combinations


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:深入认识Python中的itertools模块

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址