Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5019510
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2012-04-10 18:10:01

#yield.py

  1. #! /usr/bin/env python
  2. #coding=utf-8
  3. class Permutation:
  4.     def __init__(self, justalist):
  5.         self._data = justalist[:]
  6.         self._sofar = []
  7.     def __iter__(self):
  8.         return self.next()
  9.     def next(self):
  10.         for elem in self._data:
  11.             if elem not in self._sofar:
  12.                 self._sofar.append(elem)
  13.                 if len(self._sofar) == len(self._data):
  14.                     yield self._sofar[:]
  15.                 else:
  16.                     for v in self.next():
  17.                         yield v
  18.                 self._sofar.pop()
  19.                 
  20. a = [1,2,3]
  21. for i in Permutation(a):
  22.     print i
$ python yield.py
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
 
#yield2.py
  1. #! /usr/bin/env python
  2. #coding=utf-8
  3. import os
  4. def walk(path):
  5.     if os.path.isdir(path):
  6.         for file in os.listdir(path):
  7.             file_path=os.path.join(path, file);
  8.             for sub_file in walk(file_path):
  9.                 yield sub_file
  10.     else:
  11.         pass
  12.     yield path

  13. for file in walk("."):
  14.     print file

以上是yield的用法。这个东西不太好理解。网上有很多例子。讲的也不是很透彻。 
阅读(1037) | 评论(0) | 转发(0) |
0

上一篇:Python 深入理解yield

下一篇:yield用法说明

给主人留下些什么吧!~~