Python itertools 简单迭代器的使用

itertools

  1. 无穷迭代器
  • count(start,[step]) 从start的值开始,按照step的步长无穷计数下去,默认step为1
  • cycle(p) 循环输出p
  • repeat(elem,[n]) 重复输出elem n次,默认为无限次
  1. 根据最短输入序列长度停止的迭代器
  • chain(p,q...) 将两个对象连在一起
  • groupby(iterable,[key]) 根据元素返回值进行分组
  1. map(fun,iterable) 函数对序列进行映射
  1. 代码演示
import itertools

#从参数开始计数,创造一个无穷迭代器
list0=itertools.count(10)
j=0
for l in list0:
    print(l)
    j+=1
    if j>=5:
        break
print('=========================')

#将传入的序列无限次重复下去
list1=itertools.cycle('ABCD')
j=0
for l in list1:
    print(l)
    j+=1
    if j>=5:
        break
print('=========================')

#将第一个参数重复第二个参数的次数,若不指定第二个参数就将无穷次
list2=itertools.repeat(9,3)
for l in list2:
    print(l)
print('=========================')


list3=itertools.chain('abc','def')
for l in list3:
    print(l)
print('=========================')


#只要两个元素返回值相同,就被认为是一个组,函数的返回值作为key
for key,group in itertools.groupby('AABBACCDDA'):
    print(key,list(group))
print('=========================')


#让大小写返回值相同
for key,group in itertools.groupby('AaBbAcCdDA',lambda c:c.upper()):
    print(key,list(group))
print('=========================')

def add_one(n):
    return n+1
for i in map(add_one,[1,2,3,4,5]):
    print(i)


list4=itertools.count(1,2)
list5=list()
for i in range(10):
    list5.append(next(list4))
print(list5)
print(sum(list5))


'''
10
11
12
13
14
=========================
A
B
C
D
A
=========================
9
9
9
=========================
a
b
c
d
e
f
=========================
A ['A', 'A']
B ['B', 'B']
A ['A']
C ['C', 'C']
D ['D', 'D']
A ['A']
=========================
A ['A', 'a']
B ['B', 'b']
A ['A']
C ['c', 'C']
D ['d', 'D']
A ['A']
=========================
2
3
4
5
6
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
100
'''

你可能感兴趣的:(Python itertools 简单迭代器的使用)