Created
October 6, 2013 11:58
-
-
Save nooperpudd/6853178 to your computer and use it in GitHub Desktop.
python itertools examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from itertools import * | |
# imap | |
for i in imap(lambda x:x*2,xrange(5)): | |
print i | |
# starmap | |
values=[(1,2),(5,23),(8,9)] | |
for i in starmap(lambda x,y:(x,y,x*y),values): | |
print i | |
# izip | |
for i in izip(xrange(1,7),cycle(['a','b','c'])): | |
print i | |
# repeat | |
for i in repeat('over-and-over',5): | |
print i | |
# izip+repeat | |
for i in izip(count(),repeat('over',6)): | |
print i | |
# imap+xrange+repeat | |
for i in imap(lambda x,y:x*y, xrange(5),repeat(2)): | |
print i | |
# chain | |
for i in chain([1,2,3],['a','b','c']): | |
print i | |
# izip | |
for i in izip([1,2,3],['a','b','c']): | |
print i | |
#islice | |
for i in islice(count(),5,10,2): | |
print i | |
# tee | |
r = izip([1,3,4],[4,5,6]) | |
r1,r2=tee(r) | |
# 用于部分迭代数据结构 | |
print list(r1) | |
print list(r2) | |
# | |
# dropwhile | |
# 迭代数据过滤 | |
def f(x): | |
print "test:",x | |
return (x<1) | |
for i in [-1,0,1,2]: | |
print 'new',i | |
for i in dropwhile(f,[-1,0,2,3]): | |
print i | |
#takewhile | |
# 停止数据处理 | |
for i in takewhile(f,[-1,0,2]): | |
print i | |
# ifilter | |
# ifilterfalse | |
# 数据过滤,处理每一个数据 | |
for i in ifilter(f,[-1,0,2]): | |
print "new:tewst",i | |
class point(object): | |
def __init__(self,x,y): | |
self.x=x | |
self.y=y | |
def __repr__(self): | |
return '(%s,%s)' % (self.x,self.y) | |
def __cmp__(self,other): | |
return cmp((self.x,self.y),(other.x,other.y)) | |
data=list( | |
imap( | |
point,cycle(islice(count(),3)), | |
islice(count(),7), | |
) | |
) | |
print data | |
import pprint | |
import operator | |
print pprint.pprint(data) | |
data.sort() | |
# groupby 分组 | |
for k,g in groupby(data,operator.attrgetter('x')): | |
print k,list(g) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
0
2
4
6
8
(1, 2, 2)
(5, 23, 115)
(8, 9, 72)
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'a')
(5, 'b')
(6, 'c')
over-and-over
over-and-over
over-and-over
over-and-over
over-and-over
(0, 'over')
(1, 'over')
(2, 'over')
(3, 'over')
(4, 'over')
(5, 'over')
0
2
4
6
8
1
2
3
a
b
c
(1, 'a')
(2, 'b')
(3, 'c')
5
7
9
[(1, 4), (3, 5), (4, 6)]
[(1, 4), (3, 5), (4, 6)]
new -1
new 0
new 1
new 2
test: -1
test: 0
test: 2
2
3
test: -1
-1
test: 0
0
test: 2
test: -1
new:tewst -1
test: 0
new:tewst 0
test: 2
[(0,0), (1,1), (2,2), (0,3), (1,4), (2,5), (0,6)]
[(0,0), (1,1), (2,2), (0,3), (1,4), (2,5), (0,6)]
None
0 [(0,0), (0,3), (0,6)]
1 [(1,1), (1,4)]
2 [(2,2), (2,5)]
[Finished in 0.1s]