Python yield 详解(二)

实验了几个小时的yield,附上一段代码:

# encoding: utf-8
from collections import defaultdict, namedtuple 

def dataFromFile(fname, sep='\t'):
	file_iter = open(fname, 'rU')
	for line in file_iter:
		line = line.strip().rstrip(sep)  # Remove trailing comma
		if len(line) < 1 :
			continue

		record = frozenset(line.split(sep))
		yield record
def count(inFile):
	items = defaultdict(lambda: 0)
	processed_transactions = []
	filecount = [0]
	filecount[0] = 0
	for transaction in inFile:
		filecount[0] += 1
		processed = []
		for item in transaction:
			items[item] += 1
			processed.append(item)
		processed_transactions.append(processed)
	print processed_transactions
	print "b"
	for i in  processed_transactions:
		yield i
		print "c" 


if __name__ == '__main__':
	inFile = dataFromFile("test", "\t")
	for i in count(inFile):
		print i
		print "a"
test中内容:

f       a       c       d       g       i       m       p

a       b       c       f       l       m       o
b       f       h       j       o
b       c       k       s       p
a       f       c       e       l       p       m       n
执行结果为:

[['a', 'c', 'd', 'g', 'f', 'i', 'm', 'p'], ['a', 'c', 'b', 'f', 'm', 'l', 'o'], ['h', 'b', 'j', 'o', 'f'], ['s', 'c', 'b', 'k', 'p'], ['a', 'c', 'e', 'f', 'm', 'l', 'n', 'p']]
b
['a', 'c', 'd', 'g', 'f', 'i', 'm', 'p']
a
c
['a', 'c', 'b', 'f', 'm', 'l', 'o']
a
c
['h', 'b', 'j', 'o', 'f']
a
c
['s', 'c', 'b', 'k', 'p']
a
c
['a', 'c', 'e', 'f', 'm', 'l', 'n', 'p']
a
c

你可能感兴趣的:(python)