python中的itertools的使用详解


Posted in Python onJanuary 13, 2020

今天了解了下python中内置模块itertools的使用,熟悉下,看能不能以后少写几个for,嘿嘿?。

1.无穷的迭代器

1.1 count(start,[step])

count()接受两个参数

  • start:循环开始的数字
  • step:循环中的间隔
from itertools import count

"""
无穷的迭代器 count()
"""
c = count(0, 2)
v = next(c)
while v < 10:
  v = next(c)
  print(v, end=',')

1.2 cycle()

cycle就是一while True,无限循环里面的数字。

"""
无穷迭代器 cycle()
"""
from itertools import cycle

c = cycle('ABCD')
for i in range(10):
  print(next(c), end=',')

1.3 repeat(elem,[n])

重复迭代elem,n次

"""
无穷迭代器 repeat()
"""
from itertools import repeat

r = repeat(1, 3)
for i in range(3):
  print(next(r), end=',')

2. 迭代器

2.1 accumulate(p,[func])

使用func的函数对迭代对象p进行累积。

"""
迭代器 accumulate()
"""
from itertools import accumulate

test_list = [i for i in range(1, 11)]
for i in accumulate(test_list): # 默认是operator.add
  print(i, end=',')
print()
for i in accumulate(test_list, lambda x, y: x * y): # operator.mul
  print(i, end=',')

2.2 chain()

chain()中可以放多个迭代对象,然后一一迭代出来。

"""
迭代器 chain()
"""
from itertools import chain

ch = chain([1, 2, 3], {4: 4, 5: 5}, {6, 7, 8}, (9,), [10, [11, 12]])
for i in ch:
  print(i)

2.3 chain.from_iterable()

跟chain不同的地方在于:

  • chain: 可以接受多个迭代对象
  • chain.from_iterable():可以接受一个可以产生迭代对象的迭代器
"""
迭代器 chain.from_iterable()
"""
def gen_iterables():
  for i in range(10):
    yield range(i)

for i in chain.from_iterable(gen_iterables()):
  print(i)

2.4 compress(data,selectors)

这是就是看下这个就知道了s是selectors中的元素。
(d[0] if s[0]), (d[1] if s[1]), ...

"""
迭代器 compress
"""
from itertools import compress

print(list(compress(['A', 'B', 'C', 'D'], [0, 1, 1, 1])))

2.5 dropwhile(pred,seq)

循环开始的条件是,直到遇到第一次不满足pred条件的情况,才开始遍历。

"""
迭代器 dropwhile()
"""
from itertools import dropwhile

l = [1, 7, 6, 3, 8, 2, 10]
print(list(dropwhile(lambda x: x < 3, l)))

2.6 groupby

这个感觉挺有意思的,有点像sql中的group_by。可以对字符串,列表等进行分组。

返回键和,组里的内容

from itertools import groupby

# 对字符串进行分组
for k, g in groupby('11111234567'):
  print(k, list(g))
d = {1: 1, 2: 2, 3: 2}
# 按照字典value来进行分组
for k, g in groupby(d, lambda x: d.get(x)):
  print(k, list(g))

2.7 islice
这个就是对迭代对象进行切割,不支持负数,有点像range(1,10,2)这种

from itertools import islice
print(list(islice('ABCDEFG', 2,3, None)))

2.8 zip_longest

这个和zip很像,不同地方在于:

  • zip结束取决于里面最短的迭代对象
  • zip_longest结束取决于里面最长的迭代对象
from itertools import zip_longest

for x,y in zip_longest([1,2,3],[1,2]):
  print(x,y)
for x,y in zip([1,2,3],[1,2]):
  print(x,y)

排列组合迭代器

3.1 product

相当于 嵌套的for

“”"
排列组合迭代器 product 嵌套的for
“”"
from itertools import product
for i,j in product([1,2,3],[4,5]):
print(i,j

3.2 permutations

全排列,比如输出123的全部情况。(1,2,3),(1,3,2)…

from itertools import permutations
print(list(permutations('123')))

3.3 combinations(p,r)

从p中找出所有长度为r的排列情况… 有顺序

from itertools import combinations
print(list(combinations([1,2,3],2)))

3.4 combinations_with_replacement()

从p中找出所有长度为r的排列情况,有顺序,但包括自身就是会重复的意思。

  • combinations_with_replacement(‘ABCD', 2)
  • AA AB AC AD BB BC BD CC CD DD

了解是了解了,就是用的时候不知道能不能想起来…

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python读写Excel文件的实例
Nov 01 Python
python UNIX_TIMESTAMP时间处理方法分析
Apr 18 Python
python中利用Future对象回调别的函数示例代码
Sep 07 Python
对TensorFlow中的variables_to_restore函数详解
Jul 30 Python
python写入文件自动换行问题的方法
Jul 05 Python
3行Python代码实现图像照片抠图和换底色的方法
Oct 10 Python
Python 实现自动获取种子磁力链接方式
Jan 16 Python
python构造IP报文实例
May 05 Python
Python 如何测试文件是否存在
Jul 31 Python
python 通过 pybind11 使用Eigen加速代码的步骤
Dec 07 Python
python中str内置函数用法总结
Dec 27 Python
python 图像增强算法实现详解
Jan 24 Python
python3读取csv文件任意行列代码实例
Jan 13 #Python
pytorch程序异常后删除占用的显存操作
Jan 13 #Python
Python跑循环时内存泄露的解决方法
Jan 13 #Python
PyTorch使用cpu加载模型运算方式
Jan 13 #Python
Python如何读取文件中图片格式
Jan 13 #Python
详解python破解zip文件密码的方法
Jan 13 #Python
PyTorch 随机数生成占用 CPU 过高的解决方法
Jan 13 #Python
You might like
《五等分的花嫁》漫画完结!2020年10月第2期TV动画制作组换血!
2020/03/06 日漫
php定时计划任务的实现方法详解
2013/06/06 PHP
php class中public,private,protected的区别以及实例分析
2013/06/18 PHP
使用PHP生成二维码的两种方法(带logo图像)
2014/03/14 PHP
PHPExcel简单读取excel文件示例
2016/05/26 PHP
PHP简单读取xml文件的方法示例
2017/04/20 PHP
laravel5.1 ajax post 传值_token示例
2019/10/24 PHP
浅析PHP echo 和 print 语句
2020/06/30 PHP
Using the TextRange Object
2006/10/14 Javascript
从数组中随机取x条不重复数据的JS代码
2013/12/24 Javascript
jquery css 设置table的奇偶行背景色示例
2014/06/03 Javascript
轻松实现javascript图片轮播特效
2016/01/13 Javascript
利用js编写响应式侧边栏
2016/09/17 Javascript
js获取文件里面的所有文件名(实例)
2017/10/17 Javascript
vue.js项目nginx部署教程
2018/04/05 Javascript
从零撸一个pc端vue的ui组件库( 计数器组件 )
2019/08/08 Javascript
小程序实现投票进度条
2019/11/20 Javascript
jQuery实现评论模块
2020/08/19 jQuery
python使用htmllib分析网页内容的方法
2015/05/08 Python
Python入门学习指南分享
2018/04/11 Python
Django基础知识与基本应用入门教程
2018/07/20 Python
Python重新加载模块的实现方法
2018/10/16 Python
python3+django2开发一个简单的人员管理系统过程详解
2019/07/23 Python
PyCharm汉化安装及永久激活详细教程(靠谱)
2020/01/16 Python
详解Python中@staticmethod和@classmethod区别及使用示例代码
2020/12/14 Python
CSS3简单实现照片墙
2014/12/12 HTML / CSS
REISS美国官网:伦敦最受欢迎的时尚品牌
2019/08/16 全球购物
应届生体育教师自荐信
2013/10/03 职场文书
新闻编辑自荐信
2013/11/03 职场文书
应届生自我鉴定
2013/12/11 职场文书
应聘编辑职位自荐信范文
2014/01/05 职场文书
大学生党员自我批评
2014/02/14 职场文书
房地产项目建议书
2014/03/12 职场文书
房屋转让协议书范本
2014/04/11 职场文书
2014年学生会工作总结
2014/11/07 职场文书
2015年学校心理健康教育工作总结
2015/05/11 职场文书