【python学习】基础篇-常用模块-itertools:用于生成各种类型的迭代器,例如排列、组合、重复等

Python中的itertools模块提供了许多用于处理迭代器的函数,
这些函数可以用于生成各种类型的迭代器,例如排列、组合、重复等。
以下是一些常用的itertools函数及其用法:

  1. count(start, step)
    从start开始,以step为步长生成一个无限的整数序列。
import itertools

for i in itertools.count(1):
    print(i) # 1 2 3 4 5 6 7 8 9 10
    
  1. cycle(iterable)
    对iterable进行循环迭代,返回一个无限的迭代器。
import itertools

for i in itertools.cycle([1, 2, 3]):
    print(i) # 1 2 3 1 2 3 1 2 3 

  1. repeat(object, times)
    将object重复times次,返回一个迭代器。
import itertools

for i in itertools.repeat('a', 5):
    print(i) #a a a a a
  1. permutations(iterable, r=None)
    返回iterable中所有长度为r的元素排列组成的迭代器
    如果r为None,则返回所有可能的排列。
import itertools

for i in itertools.permutations('abc', 2):
    print(i)
    #('a', 'b') ('a', 'c') ('b', 'a') ('b', 'c') ('c', 'a') ('c', 'b')


  1. combinations(iterable, r)
    返回iterable中所有长度为r的元素组合组成的迭代器。
import itertools

for i in itertools.combinations('abc', 2):
    print(i)
    #('a', 'b') ('a', 'c') ('b', 'c')

6.product(*iterables, repeat=1)
返回iterables中所有元素的笛卡尔积组成的迭代器。
如果repeat为1,则每个元素只出现一次;
如果repeat为任意正整数n,则每个元素出现n次。

import itertools

for i in itertools.product(['a', 'b'], ['x', 'y']):
    print(i)
    # ('a', 'x') ('a', 'y') ('b', 'x') ('b', 'y')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值