python内置库-itertools

groupby

from itertools import groupby
import re

"""
groupby(iterable, key=None)
描述:相邻元素按照key分组,返回键值对,键为元素作用于key的返回值,值为一个生成器
      作用于函数的相邻元素返回的值相等,就会被放到同一个组里
      默认为相邻元素相等就放到一个组
一句话总结:
    iterable中的相邻多个元素经过key处理后结果相等的放到一个组内
"""

# 默认将相等的元素放到一个分组
for key, value in groupby('abbccc'):
    print(key, list(value))
'''
a ['a']
b ['b', 'b']
c ['c', 'c', 'c']
'''


for key, value in groupby('12345612', key=lambda x:x<'3'):
    print(f'{key}: {list(value)}')

'''
True: ['1', '2']
False: ['3', '4', '5', '6']
True: ['1', '2']
'''

# 将字符串中的数字和字母分开
def isNum(data):
    matched = re.search(r'\d+', data)
    return True if matched else False
srce_str = 'good89bad12hello'
for key, val in groupby(srce_str, lambda x: isNum(x)):
    print(f'key:{key}, value:{list(val)}')

'''
key:False, value:['g', 'o', 'o', 'd']
key:True, value:['8', '9']
key:False, value:['b', 'a', 'd']
key:True, value:['1', '2']
key:False, value:['h', 'e', 'l', 'l', 'o']
'''

accumulate : 前n项的结果

from itertools import accumulate

"""
accumulate(iterable, func)
生成一个和iterable长度一致的可迭代对象,第n个元素为对0~n元素执行func的结果, func默认为求和
"""
res_list = [1,2,3,4,5]
sum_list = list(accumulate(res_list))
min_list = list(accumulate(res_list, min))
print(sum_list)
print(min_list)
[1, 3, 6, 10, 15]
[1, 1, 1, 1, 1]

product: 笛卡尔积

from itertools import product

'''
product(*iterable, repeat=1)
功能: 可迭代对象的笛卡尔积

注意: product(A, repeat=4)  和 product(A, A, A, A)等价
       product(A, B, repeat=2) 和 product(A, B, A, B)等价
'''
A, B = 'ab', 'cd'
list(product(A, B))  # [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

list(product(A, B, repeat=2))
'''
('a', 'c', 'a', 'c')
('a', 'c', 'a', 'd')
('a', 'c', 'b', 'c')
('a', 'c', 'b', 'd')
('a', 'd', 'a', 'c')
('a', 'd', 'a', 'd')
('a', 'd', 'b', 'c')
('a', 'd', 'b', 'd')
('b', 'c', 'a', 'c')
('b', 'c', 'a', 'd')
('b', 'c', 'b', 'c')
('b', 'c', 'b', 'd')
('b', 'd', 'a', 'c')
('b', 'd', 'a', 'd')
('b', 'd', 'b', 'c')
('b', 'd', 'b', 'd')

'''

permutations:排列

from itertools import permutations
"""
permutations(iterable ,r=None)
返回可迭代序列的排列组合,按照顺序,不包含重复元素
r传入返回序列每个元素的长度
"""
for i in permutations('123'):
    print(i)
'''
('1', '2', '3')
('1', '3', '2')
('2', '1', '3')
('2', '3', '1')
('3', '1', '2')
('3', '2', '1')
'''

permutations('123', 2)
'''
('1', '2')
('1', '3')
('2', '1')
('2', '3')
('3', '1')
('3', '2')
'''

combinations: 组合

from itertools import combinations
"""
combinations(iterable, r)
返回iterable序列中长度为r的子序列。
注意:combinations 返回的是组合,,而permutations返回的是排列。
组合不关注顺序,排列关注顺序
"""
for i in combinations('123', 2):
    print(i)
'''
('1', '2')
('1', '3')
('2', '3')
'''

for i in combinations('123', 3):
    print(i)
'''
('1', '2', '3')
'''

combinations_with_replacement :自身可重复排列

from itertools import  combinations_with_replacement
"""
combinations_with_replacement(iterable, r)
返回一个可以与自身重复的元素组合,类似与combinations
"""

for i in combinations_with_replacement('123', 3):
    print(i)
'''
('1', '1', '1')
('1', '1', '2')
('1', '1', '3')
('1', '2', '2')
('1', '2', '3')
('1', '3', '3')
('2', '2', '2')
('2', '2', '3')
('2', '3', '3')
('3', '3', '3')
'''

compress : 数据筛选

from itertools import compress
"""
compress(data, selectors)
根据selectors中的真值,返回data中对应的元素
"""
data =    ['a', 'b', 'c', 'd', 'e', 'f']
selectors= [1,   0,   1,   0,   0,   1]

for i in compress(data , selectors):
    print(i)
'''
a
c
f
'''

dropwhile 数据剔除

from itertools import dropwhile

"""
dropwhile(function, iterable)
iterable中的元素执行function为False时,开始迭代序列(即返回后面的元素)
function 为True则去除
取后半段
"""
for i in dropwhile(lambda x: x < 5, [4, 1, 5, 0, 1]):
    print(i)
'''
5
0
1
'''

takewhile 数据选取

from itertools import takewhile
from itertools import count

"""
takewhile(key, iterable)
描述:返回序列,当key为true时截止
取前半段
"""
my_iter = count(1)
for i in takewhile(lambda x: x < 5, my_iter):
    print(i)
'''
1
2
3
4
'''

filterfalse 数据过滤

from itertools import filterfalse

"""
filterfalse(function, iterable)
function 返回True或者False
返回不符合function条件的项,如果function为None,返回iterable中为False的元素
"""
for i in filterfalse(lambda x: x < 10, [1, 2, 10, 9, 20]):
    print(i)
'''
10
20
'''

for i in filterfalse(None, [1, 0, 10, False, []]):
    print(i)
'''
0
False
[]
'''

islice 数据切片

from itertools import islice
from itertools import count
"""
islice(iterable, start, stop, step)
返回序列iterable中从start索引开始,到stop索引结束的子序列
没有start时默认start为0
"""
for i in islice(count(1), 3, 5):
    print(i)
'''
4
5
'''

for i in islice(count(1), 0, 10, 2):
    print(i)
'''
1
3
5
7
9
'''

starmap 数据映射,和map类似

from itertools import starmap
"""
starmap(function, seq)
对seq中的每一项执行function函数

说明:对iterable进行映射操作,参考map函数。两者区别在于:
func有多个参数时,startmap为func(*arg)用的是可变参数,
map为func(arg1,arg2)用的是位置参数
"""
srce_list = [[1,2], [10,22], [5,9]]
for i in starmap(max, [[1,2], [10,22], [5,9]]):
    print(i)
'''
2
22
9
'''

print(list(map(max, srce_list)))  # 和map函数貌似没有区别
'''  [2, 22, 9] '''

count 计步 计数

from itertools import count

"""
count(start=0, step=1)
描述: 生成从start开始,步长为step的无限序列
"""
my_iter = count(10, 1)
print(list(my_iter))  # 注意,这种打印会导致卡死

cycle 无线循环,往复迭代

from itertools import cycle

'''
    cycle(iterable)
    描述:入参一个可迭代元素,无限循环这个可迭代元素
'''
my_iter = cycle('abc')  # 一直循环['a', 'b', 'c', 'a', 'b', 'c']
for i in my_iter:
    print(i)
    break

repeat 重复

from itertools import repeat

'''
repeat(obj, times)
讲一个元素重复times次,times默认为无限多
'''
my_iter = repeat('abc', 3)  # ['abc', 'abc', 'abc']

chain 迭代器拼接

from itertools import chain
"""
chain(*iterabels)
将多个可迭代对象组合起来
"""
list(chain('abc', 'def'))  # ['a', 'b', 'c', 'd', 'e', 'f']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值