python迭代器的使用方法实例

WBOY
Release: 2016-06-06 11:28:25
Original
1170 people have browsed it

什么是迭代器?

迭代器是带有next方法的简单对象,当然也要实现__iter__函数。迭代器能在一序列的值上进行迭代,当没有可供迭代时,next方法就会引发StopIteration 的异常。python中有很多的对象都是迭代器,例如:列表,元素,字符串,文件,映射,集合

如何使用迭代器?

1. for 变量 in 可迭代对象

代码如下:


    list1 = [1,2,3,4,5]

for ele in list1:
    print ele,

结果为:1 2 3 4 5

2. if 变量 in 可迭代对象

代码如下:


list1 = [1,2,3,4,5]
var = 1

if var in list1:
    print 'yes!'
else:
    print 'No'

3. 变量 = iter(可迭代对象)

代码如下:


it = iter([1,2,3,4])

print it.next()

print it.next()

print it.next()

结果为:

1
2
3

最后,总结一下:迭代器就是一对象

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template