码迷,mamicode.com
首页 > 编程语言 > 详细

Python 迭代器

时间:2017-10-11 19:21:11      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:元组   迭代   class   函数   pid   bsp   异常   字符   cep   

iter()函数和next()函数

使用iter(序列)函数可以获得一个迭代器,使用next(迭代器)函数可以获得迭代器中的下一条数据,例如;

l = [1,2,3]
s = ‘hello world‘
t = (1,2,3,‘hello‘)
 
it1 = iter(l)
it2 = iter(s)
it3 = iter(t)
 
print(next(it1)) # 1
print(next(it2)) # h
print(next(it3)) # 1

StopIteration 异常

当迭代器中没有数据时,会抛出一个StopIteration 异常,利用该异常判断迭代结束,例如:

l = [1,2,3]
it = iter(l)
while True:
    try:
        x = next(it)
        print(x)
    except StopIteration as si:
        # print(‘end‘)
        break
# 1 2 3

迭代字符串、列表、元组和字典

l = [1,2,3]
s = ‘hello world‘
t = (1,2,3,‘hello‘)
 
it1 = iter(l)
it2 = iter(s)
it3 = iter(t)
 
print(next(it1)) # 1
print(next(it2)) # h
print(next(it3)) # 1
 
# 字典
d = {‘pid‘:‘123‘,‘name‘:‘tom‘,‘age‘:‘20‘}
it = iter(d) # keys
 
for k in it:
    v = d[k]
    print(k,v ,end=‘ ‘)

使用for/while循环迭代

l = [1,2,3]


it = iter(l)
 
for x in it:
    print(x)
 
# 1 2 3


it = iter(l)
 
while True:
    try:
        x = next(it)
        print(x)
    except StopIteration as si:
        break
# 1 2 3

 

 

 

Python 迭代器

标签:元组   迭代   class   函数   pid   bsp   异常   字符   cep   

原文地址:http://www.cnblogs.com/lcgsmile/p/7652048.html

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