Home Backend Development Python Tutorial 详解Python迭代和迭代器

详解Python迭代和迭代器

Jun 10, 2016 pm 03:05 PM

我们将要来学习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

Copy after login

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')
Copy after login

那么,st是可迭代的吗?

>>> iter(st)

TypeError: 'String' object is not iterable

Copy after login

你可能会有几个问题要问:

怎么让自定义的类型可迭代?
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>
Copy after login

在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>
Copy after login

‘itr'也会调用'iterable.__getitem__()',所以我们用'__getitem__'方法让String类型可迭代。

如果在String类中同时使用'__iter__()'和'__getitem__()',就只有'__iter__'会起作用。

自动迭代

for循环会自动迭代

for x in iterable:
  print x
Copy after login

我们可以不用for循环来实现吗?

def iterate_while(iterable):
  index = 0
  while(i< len(iterable)):
    print iterable[i]
    i +=1
Copy after login

这样做对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
Copy after login

前面我们看过了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
Copy after login

我们学了够多的迭代和迭代器,在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()
Copy after login

我们来用`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
Copy after login

xrange

从一个问题开始——xrange是迭代还是迭代器?

我们来看看

>>> x = xrange(10)
>>> type(x)
<type 'xrange'>
Copy after login

几个关键点:

1. `iter(xrange(num))`应该被支持
2. 如果`iter(xrange(num))`返回同样的对象(xrange类型)那xrange就是迭代器
3. 如果`iter(xrange(num))`返回一个迭代器对象那xrange就是迭代

>>> iter(xrange(10))
<rangeiterator object at 0x0264EFE0>
Copy after login

它返回了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()
Copy after login

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

Copy after login

以上就是本文的全部内容,希望对大家学习掌握Python迭代和迭代器有所帮助。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

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

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

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 in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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 without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

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...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

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 by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

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

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

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

See all articles