一、反向迭代:reversed()

>>> a
[1, 2, 3, 4]
>>> for x in reversed(a):
... print(x, end=' ')
...
4 3 2 1

#反向迭代只有在待处理的对象具有确定的大小或者对象实现了__reversed()__特殊方法时才能奏效,否则必须先将对象转化为列表(可能消耗大量内存)

>>> with open('/etc/passwd', 'rt') as file:
... for x in reversed(file): #要用list(file)
... print(x)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: argument to reversed() must be a sequence

二、迭代器切片:itertools.islice

import itertools
>>> def count(n):
... while True:
... yield n
... n += 1
...
>>> for x in itertools.islice(count(0), 2, 10): #相当于列表切片取[2:10]
... print(x, end=' ')
...
2 3 4 5 6 7 8 9
>>>for x in itertools.islice(count(0), 5, None):    #相当于列表切片取[5:]
... print(x, end=' ')
... if x >10:
... break
...
5 6 7 8 9 10
>>> for x in itertools.islice(count(0), 5): #相当于列表切片取[:5]
... print(x, end=' ')
...
0 1 2 3 4

#迭代器和生成器无法进行普通的切片操作(其长度不确定且没有实现索引),islice会产生一个新迭代器,消耗掉初始迭代序列中的所有数据

三、以索引-值对的形式迭代序列:enumerate

>>> a
[1, 2, 3, 4]
>>> for index, value in enumerate(a, 1): #从1开始计数,语法:enumerate(iterable[, start])
... print(index, value)
...
1 1
2 2
3 3
4 4

#enumerate的返回值是一个迭代器,元素是元组

四、同时迭代多个序列

  并行成对迭代:zip()、itertools.zip_longest()

>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4, 8, 9]
>>> for x, y in zip(a, b):
... print(x, y)
...
1 1
2 2
3 3
4 4
>>> for x, y in itertools.zip_longest(a, b):
... print(x, y)
...
1 1
2 2
3 3
4 4
None 8
None 9
>>> for x, y in itertools.zip_longest(a, b, fillvalue=0):
... print(x, y)
...
1 1
2 2
3 3
4 4
0 8
0 9

  串行顺序迭代:itertools.chain()

>>> for x in itertools.chain(a, b):
... print(x)
...
1
2
3
4
1
2
3
4
8
9

  串行交叉迭代:heapq.merge()

>>> import heapq
>>> for x in heapq.merge(a, b):
... print(x)
...
1
1
2
2
3
3
4
4
8
9

Python3 From Zero——{最初的意识:004~迭代器和生成器}的更多相关文章

  1. python--3、 可迭代对象、迭代器、生成器

    可迭代对象 iterable 可直接作用于for循环的对象统称为可迭代对象. 有 list. dict.tuple.set.str等数据类型,还有 generator(包括生成器和带yield的gen ...

  2. Python3 From Zero——{最初的意识:000~Initial consciousness}

    http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000 a.编码 默认情况下,Python ...

  3. Python3 From Zero——{最初的意识:008~初级实例演练}

    一.构显国际橡棋8x8棋盘 #!/usr/bin/env python3 #-*- coding:utf-8 -*- color_0="\033[41m \033[00m" col ...

  4. Python3 From Zero——{最初的意识:006~数据编码与处理}

    一.读写CSV数据: #!/usr/bin/env python3 #-*- coding=utf8 -*- import csv with open('kxtx.csv', 'rt') as f: ...

  5. Python3 From Zero——{最初的意识:002~字符串和文本}

    一.使用多个界定符分割字符串 字符串.split(',')形式只适用于单一分割符的情况:多分割符同时应用的时候,可使用re.split() >>> line = 'asdf fjdk ...

  6. Python3 From Zero——{最初的意识:001~数据结构和算法}

    一.从队列两端高效插入.删除元素,及保留固定数量的数据条目: collections.deque([iterable[,maxlen=N]]) a = collections.deque([1, 2] ...

  7. Python3 From Zero——{最初的意识:007~函数}

    一.编写可接受任意数量参数的函数:*.** >>> def test(x, *args, y, **kwargs): ... pass ... >>> test(1 ...

  8. Python3 From Zero——{最初的意识:005~文件和I/O}

    一.输出重定向到文件 >>> with open('/home/f/py_script/passwd', 'rt+') as f1: ... print('Hello Dog!', ...

  9. Python3 From Zero——{最初的意识:003~数字、日期、时间}

    一.对数值进行取整:round(value,ndigits) >>> round(15.5,-1) #可以取负数 20.0 >>> round(15.5,0) #当 ...

随机推荐

  1. [Android开发] 代码code设置9.png/9-patch 图片背景后,此view中的TextView等控件显示不正常(常见于listview中)

    == 0) { convertView.setBackgroundResource(R.drawable.list_gray_9); } else { convertView.setBackgroun ...

  2. NX二次开发-NXOpenC++ Example

    NxOpenC++ Example NXOpen::WCS wcs坐标系 https://www.cnblogs.com/nxopen2018/p/11368763.html NXOpen::Draw ...

  3. SVG和canvas

    1.SVG实现的圆环旋转效果 参考:http://www.softwhy.com/article-6472-1.html 2.SVG中的图形可以通过  transform="matrix(0 ...

  4. (转)websocket

    作者:Ovear链接:https://www.zhihu.com/question/20215561/answer/40316953来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请 ...

  5. share memory

    header for public argument:shmdata.h #define TEXT_SZ 2048 struct shared_use_st { int written; char t ...

  6. Dubbo入门到精通学习笔记(四):持续集成管理平台之Maven私有库和本地库的安装与配置

    文章目录 介绍 Maven私有库和本地库的安装与配置 Nexus安装 Nexus 配置(登录后) 介绍 如果构建的Maven项目本地仓库没有对应的依赖包,那么就会去Nexus私服去下载, 那么如果Ne ...

  7. 【Java多线程系列五】列表类

    一些列表类及其特性  类 线程安全 Iterator 特性 说明 Vector 是 fail-fast 内部方法用synchronized修饰,因此执行效率较低 1. 线程安全的列表类并不意味着调用它 ...

  8. 将本地已有的一个项目上传到新建的git仓库的方法

    将本地已有的一个非git项目上传到新建的git仓库的方法一共有两种. 一. 克隆+拷贝 第一种方法比较简单,直接用把远程仓库拉到本地,然后再把自己本地的项目拷贝到仓库中去.然后push到远程仓库上去即 ...

  9. 20140724 菜单制作:制表位(段落->制表位->)

    1.菜单制作:制表位(段落->制表位->) 叶轩楠·········· 上海大学 轩楠叶·········· 上海大学 楠轩叶·········· 上海大学 选完后要选“设置” 2.光盘制 ...

  10. idea plugin 进度条

    ProgressManager.getInstance().run(new Task.Backgroundable(project, "Switching Env") { @Ove ...