博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python核心编程:学习笔记3--迭代器,列表解析
阅读量:7016 次
发布时间:2019-06-28

本文共 1583 字,大约阅读时间需要 5 分钟。

  hot3.png

1. 迭代器和iter()函数

    迭代器是一组数据结构,迭代器有一个next()方法的对象,而不是通过索引来计数.通过next()将条目全部取出后,会引发一个StopIteration异常,这并不是表示错误发生,只是告诉外部调用者,迭代完成.

1. 使用迭代器

1. 序列

>>> myTuple = (123, "xyz", 45.67)>>> i = iter(myTuple)>>> i.__next__()123>>> i.__next__()'xyz'>>> i.__next__()45.67>>> i.__next__()Traceback (most recent call last):  File "
", line 1, in
i.__next__()StopIteration
    所以,对于for循环:
for i in seq:    do_something_to(i)
实际上等价于:
fetch = iter(seq)while True:    try:        i = fetch.__next__()    except StopIteration:        break    do_something_to(i)

2. 字典

    字典的迭代器会遍历它的键(key):

>>> dict1 = {"x" : 1, "y" : 2}>>> for key in dict1:	print("key:%s, value:%s" % (key, dict1[key]))	key:y, value:2key:x, value:1

3. 文件

    文件对象生成的迭代器会自动调用readline()方法.这样,循环就可以访问文本文件的所有行:

>>> with open("test.txt") as fobj:	for eachLine in fobj:		print(eachLine)		hello worldi love this worldand i love python too

2. 列表解析

    列表解析的语法如下:

[expr for iter_var in iterable]
    这个语句的核心是for循环,它迭代iterable对象的所有条目.前边的expr应用于序列的每个成员,最后的结果是该表达式产生的列表:
>>> [x ** 2 for x in range(6)][0, 1, 4, 9, 16, 25]
    而我们甚至可以加上if判断:
>>> [x ** 2 for x in range(6) if x > 3][16, 25]
    而列表中还可以存在双层for循环:
>>> [(x + 1, y + 1) for x in range(3) for y in range(5)][(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)]
    等价于:
>>> num = []>>> for x in range(3):	for y in range(5):		num.append((x + 1, y + 1))		>>> num[(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)]

转载于:https://my.oschina.net/voler/blog/374000

你可能感兴趣的文章
jdk环境变量配置
查看>>
为网卡配置多个IP地址(windows)
查看>>
句柄的理解
查看>>
手机网络连接问题
查看>>
Go -- runtime.Gosched()的作用分析
查看>>
Java Lambda 表达式 对 Map 对象排序
查看>>
WIndows 使用VS编译 Lua5
查看>>
转 VB ListView控件各种操作详解
查看>>
查看name的状态,是属于active还是standby
查看>>
<LeetCode OJ> 337. House Robber III
查看>>
PSR规范
查看>>
[Javascript] this in Function Calls
查看>>
MinGW32和64位交叉编译环境的安装和使用
查看>>
laravel 增加不存在数据库的字段
查看>>
什么是“单播”“组播”和“多播”
查看>>
flex---->图表控件
查看>>
[游泳] developing A Good Mindset when learning freestyle_1
查看>>
关于Windows 8 用户使用习惯调查结果
查看>>
JAVA代码注释
查看>>
我也说 IEnumerable,ICollection,IList,List之间的区别
查看>>