参考: http://blog.csdn.net/xiaocaiju/article/details/6968123 1. chain的使用 - import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- for item in itertools.chain(listone,listtwo):
- print item
输出:a b c 11 22 abc
2. count的使用
- i = 0
- for item in itertools.count(100):
- if i>10:
- break
- print item,
- i = i+1
-
功能:从100开始数10个数,cout返回一个无界的迭代器,小菜鸟我不会控制了,就引入了一个计数I,让它计数10次。。
输出:100 101 102 103 104 105 106 107 108 109 110
3.cycle的使用
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
-
- for item in itertools.cycle(listone):
- print item,
打印出a b c a b c a b c a b c a b c a b c a b c a b c a b c...
功能:从列表中取元素,到列表尾后再从头取...
无限循环,因为cycle生成的是一个无界的失代器
4.ifilter的使用
ifilter(fun,iterator)
返回一个可以让fun返回True的迭代器,
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
-
- def funLargeFive(x):
- if x > 5:
- return True
-
- for item in itertools.ifilter(funLargeFive,range(-10,10)):
- print item,
结果:6 7 8 9
5. imap的使用
imap(fun,iterator)
返回一个迭代器,对iterator中的每个项目调用fun
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- listthree = [1,2,3]
- def funAddFive(x):
- return x + 5
- for item in itertools.imap(funAddFive,listthree):
- print item,
返回:6 7 8 对listthree中的元素每个加了5后返回给迭代器
6.islice的使用
islice()(seq, [start,] stop [, step])
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- listthree = listone + listtwo
- for item in itertools.islice(listthree,3,5):
- print item,
功能:返回迭代器,其中的项目来自 将seq,从start开始,到stop结束,以step步长切割后
打印出:11 22
7.izip的使用
izip(*iterator)
- import itertools
- listone = ['a','b','c']
- listtwo = ['11','22','abc']
- listthree = listone + listtwo
- for item in itertools.izip(listone,listtwo):
- print item,
结果:('a', '11') ('b', '22') ('c', 'abc')
功能:返回迭代器,项目是元组,元组来自*iterator的组合
8. repeate
repeate(elem [,n])
- import itertools
- listone = ['a','b','c']
- for item in itertools.repeat(listone,3):
- print item,
结果:['a', 'b', 'c'] ['a', 'b', 'c'] ['a', 'b', 'c']
9. 参考:http://blog.csdn.net/xiaocaiju/article/details/6969401 生成器表达 式是用来生成函数调用时序列参数的一种迭代器写法
生成器对象可以遍历或转化为列表(或元组等数据结构),但不能切片(slicing)。当函数的唯一的实参是可迭代序列时,便可以去掉生成器表达式两端>的圆括号,写出更优雅的代码:
>>>> sum(i for i in xrange(10))
45
sum声明:
sum( iterable[,
start])
Sums start and the items of an iterable from left to right and returns the total.
start defaults to 0. The
iterable‘s items are normally numbers, and are not allowed to
be strings. The fast, correct way to concatenate a sequence of strings
is by calling
''.join(sequence). Note that
sum(range(n),
m) is equivalent to reduce(operator.add,
range(n), m) To add floating point values with extended precision, see
math.fsum().
参数要求传入 可迭代序列,我们传入一个生成器对象,完美实现。。。
注意区分下面代码:
上面的j为生成器类型,下面的j为list类型
- j = (i for i in range(10))
- print j,type(j)
- print '*'*70
-
- j = [i for i in range(10)]
- print j,type(j)
结果:
at 0x01CB1A30>
**********************************************************************
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|