详解Python迭代和迭代器
我们将要来学习python的重要概念迭代和迭代器,通过简单实用的例子如列表迭代器和xrange。
可迭代
一个对象,物理或者虚拟存储的序列。list,tuple,strins,dicttionary,set以及生成器对象都是可迭代的,整型数是不可迭代的。如果你不确定哪个可迭代哪个不可以,你需要用python内建的iter()来帮忙。
>>> iter([1,2,3]) <listiterator object at 0x026C8970> >>> iter({1:2, 2:4}) <dictionary-keyiterator object at 0x026CC1B0> >>> iter(1234) Traceback (most recent call last): File "<pyshell#145>", line 1, in <module> iter(1234) TypeError: 'int' object is not iterable
iter()为list返回了listiterator对象,为dictionary返回了dictionary-keyiterator对象。类似对其他可迭代类型也会返回迭代器对象。
iter()用在自定义的类型会怎样呢?我们先自己定义一个String类:
class String(object): def __init__(self, val): self.val = val def __str__(self): return self.val st = String('sample string')
那么,st是可迭代的吗?
>>> iter(st) TypeError: 'String' object is not iterable
你可能会有几个问题要问:
怎么让自定义的类型可迭代?
iter()究竟做了些什么?
让我们补充String类来找找答案
class String(object): def __init__(self, val): self.val = val def __str__(self): return self.val def __iter__(self): print "This is __iter__ method of String class" return iter(self.val) #self.val is python string so iter() will return it's iterator >>> st = String('Sample String') >>> iter(st) This is __iter__ method of String class <iterator object at 0x026C8150>
在String类中需要一个'__iter__'方法把String类型变成可迭代的,这就是说'iter'内部调用了'iterable.__iter__()'
别急,不是只有增加'__iter()'方法这一种途径
class String(object): def __init__(self, val): self.val = val def __str__(self): return self.val def __getitem__(self, index): return self.val[index] >>> st = String('Sample String') >>> iter(st) <iterator object at 0x0273AC10>
‘itr'也会调用'iterable.__getitem__()',所以我们用'__getitem__'方法让String类型可迭代。
如果在String类中同时使用'__iter__()'和'__getitem__()',就只有'__iter__'会起作用。
自动迭代
for循环会自动迭代
for x in iterable: print x
我们可以不用for循环来实现吗?
def iterate_while(iterable): index = 0 while(i< len(iterable)): print iterable[i] i +=1
这样做对list和string是管用的,但对dictionary不会奏效,所以这绝对不是python式的迭代,也肯定不能模拟for循环的功能。我们先看迭代器,等下回再过头来。
迭代器
关于迭代器先说几条………..
1. 迭代器对象在迭代过程中会会产生可迭代的值,`next()`或者`__next()__`是迭代器用来产生下一个值的方法。
2. 它会在迭代结束后发出StopIteration异常。
3. `iter()`函数返回迭代器对象
4. 如果`iter()`函数被用在迭代器对象,它会返回对象本身
我们试一试模仿for循环
def simulate_for_loop(iterable): it = iter(iterable) while(True): try: print next(it) except StopIteration: break >>> simulate_for_loop([23,12,34,56]) 23 12 34 56
前面我们看过了iterable类,我们知道iter会返回迭代器对象。
现在我们试着理解迭代器类的设计。
class Iterator: def __init__(self, iterable) self.iterable = iterable . . def __iter__(self): #iter should return self if called on iterator return self def next(self): #Use __next__() in python 3.x if condition: #it should raise StopIteration exception if no next element is left to return raise StopIteration
我们学了够多的迭代和迭代器,在python程序中不会用到比这更深的了。
但是为了学习的目的我们就到这儿。。。。
列表迭代器
你可能会在面试中写这个,所以打起精神来注意了
class list_iter(object): def __init__(self, list_data): self.list_data = list_data self.index = 0 def __iter__(self): return self def next(self): #Use __next__ in python 3.x if self.index < len(self.list_data): val = self.list_data[self.index] self.index += 1 return val else: raise StopIteration()
我们来用`list_iter`自己定义一个列表迭代器
class List(object): def __init__(self, val): self.val = val def __iter__(self): return list_iter(self.val) >>> ls = List([1,2,34]) >>> it = iter(ls) >>> next(it) 1 >>> next(it) 2 >>> next(it) 34 >>> next(it) Traceback (most recent call last): File "<pyshell#254>", line 1, in <module> next(it) File "<pyshell#228>", line 13, in next raise StopIteration() StopIteration
xrange
从一个问题开始——xrange是迭代还是迭代器?
我们来看看
>>> x = xrange(10) >>> type(x) <type 'xrange'>
几个关键点:
1. `iter(xrange(num))`应该被支持
2. 如果`iter(xrange(num))`返回同样的对象(xrange类型)那xrange就是迭代器
3. 如果`iter(xrange(num))`返回一个迭代器对象那xrange就是迭代
>>> iter(xrange(10)) <rangeiterator object at 0x0264EFE0>
它返回了rangeiterator,所以我们完全可以叫它迭代器。
让我们用最少的xrange函数实现自己的xrange
xrange_iterator
class xrange_iter(object): def __init__(self, num): self.num = num self.start = 0 def __iter__(self): return self def next(self): if self.start < self.num: val = self.start self.start += 1 return val else: raise StopIteration()
my xrange
class my_xrange(object): def __init__(self, num): self.num = num def __iter__(self): return xrange_iter(self.num) >>> for x in my_xrange(10): print x, 0 1 2 3 4 5 6 7 8 9
以上就是本文的全部内容,希望对大家学习掌握Python迭代和迭代器有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.
