#yield.py
- #! /usr/bin/env python
- #coding=utf-8
- class Permutation:
- def __init__(self, justalist):
- self._data = justalist[:]
- self._sofar = []
- def __iter__(self):
- return self.next()
- def next(self):
- for elem in self._data:
- if elem not in self._sofar:
- self._sofar.append(elem)
- if len(self._sofar) == len(self._data):
- yield self._sofar[:]
- else:
- for v in self.next():
- yield v
- self._sofar.pop()
-
- a = [1,2,3]
- for i in Permutation(a):
- 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
- #! /usr/bin/env python
- #coding=utf-8
- import os
- def walk(path):
- if os.path.isdir(path):
- for file in os.listdir(path):
- file_path=os.path.join(path, file);
- for sub_file in walk(file_path):
- yield sub_file
- else:
- pass
- yield path
- for file in walk("."):
- print file
以上是yield的用法。这个东西不太好理解。网上有很多例子。讲的也不是很透彻。
阅读(1074) | 评论(0) | 转发(0) |