#无限迭代器count
from itertools import *
a=count()
results=[]
while True:
val=a.__next__()
results.append(val)
if len(results)==10:
break
print(results)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#repeat
res=repeat('a',10)
for i in res:
print(i)
a
a
a
a
a
a
a
a
a
a
#cycle
cycle('abc')
<itertools.cycle at 0x5381a68>
res=accumulate([1,2,3])
for i in res:
print(i)
1
3
6
#chain
l1=[1,2,3]
l2=[4,5,6]
for i in chain(l1,l2):
print(i)
1
2
3
4
5
6
for i in dropwhile(lambda x: x<5, [1,4,6,4,1]):
print(i) #前面开始的小于5的数被丢弃,后面的不计算
6
4
1
#takewhile保留符合条件的
for i in takewhile(lambda x: x<5, [1,4,6,4,1]):
print(i)
1
4
#切片
for i in islice('ABCDEFG', 2,4):
print(i)
C
D
for i in compress('ABCDEF', [1,None,1,0,1,1]):
print(i)
A
C
E
F
#zip_longest(),类似于zip,多余的项为none或指定
for i,j in dict(zip_longest('ABCD', 'xy',fillvalue='novalue')).items():
print(i,j)
A x
B y
C novalue
D novalue
#tee(),返回多个独立迭代器
i1,i2=tee(range(5))
print(list(i1))
print(list(i2))
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
#groupby,分组
#返回姓名开头的分组数据
from operator import itemgetter
def get_startname(name):
if name.split()[0]=='zhang':
return 'zh'
elif name.split()[0]=='li':
return 'li'
d1={"id":"001",
"name":"zhang san"
}
d2={"id":"002",
"name":"li si"
}
d3={"id":"003",
"name":"zhang wu"
}
l1=[]
l1.append(d1)
l1.append(d2)
l1.append(d3)
l1 = sorted(l1,key = itemgetter('name'))
datas=groupby(l1, lambda p:get_startname(p['name']))
for key,group in datas:
print(key,list(group))
li [{'id': '002', 'name': 'li si'}]
zh [{'id': '001', 'name': 'zhang san'}, {'id': '003', 'name': 'zhang wu'}]
网友评论