码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器

时间:2018-08-11 01:14:04      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:iterable   ash   iter   enter   列表   查看   iss   style   stop   

迭代器

使用dir来查看该数据包含了那些方法

print(dir(str)) 
运行结果:
[__add__, __class__, __contains__, __delattr__, __dir__, __doc__, __eq__, __format__, __ge__, __getattribute__, __getitem__, __getnewargs__, __gt__, __hash__, __init__, __init_subclass__, __iter__, __le__, __len__, __lt__, __mod__, __mul__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__, __rmod__, __rmul__, __setattr__, __sizeof__, __str__, __subclasshook__, capitalize, casefold, center, count, encode, endswith, expandtabs, find, format, format_map, index, isalnum, isalpha, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip, maketrans, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill]

用来遍历列表,字符串,元祖....可迭代对象

可迭代对象: Iterable, 里面有__iter__()可以获取迭代器, 没有__next__()
迭代器: Iterator, 里面有__iter__()可以获取迭代器, 还有__next__()

lst = [1, 2, 3]
it = lst.__iter__()

print("__iter__" in dir(it))
print("__next__" in dir(it))

from collections import Iterable  # 可迭代对象
from collections import Iterator    # 迭代器

print(isinstance(lst, Iterable))
print(isinstance(lst, Iterator))

print(isinstance(it, Iterable))
print(isinstance(it, Iterator))

迭代器特点:

1. 只能向前
2. 惰性机制
3. 省内存(生成器)

for循环的内部机制

1. 首先获取到迭代器
2. 使用while循环获取数据
3. it.__next__()来获取数据
4. 处理异常 try:xxx except StopIteration:

lst = ["", "", ""]
a = lst.__iter__()
while True:
    try:
        s = a.__next__()
        print(s)
    except StopIteration:
        break

迭代器

标签:iterable   ash   iter   enter   列表   查看   iss   style   stop   

原文地址:https://www.cnblogs.com/jiaqi-666/p/9457573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!