Python itertools库函数大全

本文详细介绍了Python的itertools模块中的各种迭代器函数,如累积计算、连接迭代、组合与排列、重复元素处理等,展示了如何灵活运用这些函数进行数据处理和操作。
摘要由CSDN通过智能技术生成

1. accumulate

accumulate函数用于返回一个累积的迭代器,它逐个计算传入迭代器中的元素的累积值

itertools中的accumulate函数接受两个参数:

  1. iterable:这是要进行累积操作的可迭代对象,例如列表、元组或任何可迭代的数据结构。
  2. func (可选):这是一个二元函数(只接受两个参数),用于指定如何计算累积值。如果未提供此参数,accumulate将默认使用加法来计算累积值。

1.1 对数进行累计计算

import itertools

data = [1, 2, 3, 4, 5]

accumulated_data = itertools.accumulate(data)
print(accumulated_data)

for item in accumulated_data:
    print(item)

image-20240227140842912

import itertools

def custom_multiply(x, y):
    return x * y

data = [1, 2, 3, 4, 5]

accumulated_data = itertools.accumulate(data, custom_multiply)

for item in accumulated_data:
    print(item)

image-20240227141152798

1.2 对字符串进行拼接

import itertools

data = ['a', 'bb', 'ccc', 'dddd']

accumulated_data = itertools.accumulate(data, lambda x, y: x + y)

for item in accumulated_data:
    print(item)

image-20240227141327697

2. chain

将多个可迭代对象连接成一个单一的迭代器。它会逐个迭代每个可迭代对象,并在第一个对象耗尽后继续迭代下一个对象,依此类推,直到所有对象都被迭代完为止。

import itertools

a = [1, 2, 3]
b = ['a', 'b', 'c']

chained_iterable = itertools.chain(a, b)

for item in chained_iterable:
    print(item)

image-20240227141629565

3. combinations(组合)

用于生成指定长度的所有可能的组合,其中组合元素取自于给定的可迭代对象。这个函数返回一个迭代器,该迭代器产生元组,每个元组包含指定长度的元素组合。

import itertools

a = ['a', 'b', 'c', 'd']

# 从a中任选三个元素进行排列
for item in itertools.combinations(a, 3):
    print(item)

image-20240227141904765

4. combinations_with_replacement

combinations_with_replacement函数与combinations函数类似,但它允许生成包含重复元素的组合。也就是说,它会生成所有可能的长度为 r 的组合,其中元素可以从可迭代对象中重复选择。

import itertools

a = ['a', 'b', 'c', 'd']

for item in itertools.combinations_with_replacement(a, 3):
    print(item)

image-20240227142148207

5. compress

它接受两个可迭代对象作为参数,并返回一个迭代器,该迭代器生成来自第一个可迭代对象中对应位置为True的元素.

具体来说,compress函数通过将第一个可迭代对象中对应位置为True的元素与第二个可迭代对象进行关联,来过滤和选择元素。

import itertools

data = ['a', 'b', 'c', 'd', 'e']
selectors = [True, False, True, False, True]

filtered_data = itertools.compress(data, selectors)

for item in filtered_data:
    print(item)

image-20240227142606362

其中selectors并不只能是True或False。

False可以用None、0 (整数0)、0.0 (浮点数0)、‘’ (空字符串)、空列表、元组、集合和字典、其他情况下的空对象来代替

除此之外其它所有值都当作True

6. count

用于生成一个无限的迭代器,该迭代器会从指定的起始值开始,按照指定的步长递增。

count函数接受两个参数:

  1. start (可选):这是起始值,默认为0。
  2. step (可选):这是递增步长,默认为1。
import itertools

# 从3开始,每次增加2
counter = itertools.count(start=3, step=2)

# 打印前5个元素
for _ in range(5):
    print(next(counter))

image-20240227143150178

因为这个迭代器是会无限迭代下去的,用for循环遍历counter的话这个循环就不会停止。用next的话就只会打印该迭代器的下一个元素

7. cycle

用于创建一个无限循环迭代器,该迭代器会无限重复指定的可迭代对象中的元素。

cycle函数接受一个可迭代对象作为参数,并返回一个迭代器,该迭代器会不断重复这个可迭代对象中的元素。

import itertools

data = ['a', 'b']

cycler = itertools.cycle(data)

# 打印前10个元素
for _ in range(10):
    print(next(cycler))

image-20240227143525168

8. dropwhile

用于创建一个迭代器,该迭代器会跳过满足指定条件的元素,一旦遇到不满足条件的元素,就会返回后面的所有元素。

dropwhile 函数接受两个参数:

  1. predicate:这是一个函数或者可调用对象,用于定义条件。dropwhile 将会一直跳过可迭代对象中的元素,直到该条件函数返回 False
  2. iterable:这是要从中过滤元素的可迭代对象。
import itertools

data = [1, 2, 3, 4, 5, 6]

def condition(x):
    return x <= 4

filtered_data = itertools.dropwhile(condition, data)

# 打印过滤后的元素
for item in filtered_data:
    print(item)

image-20240227143926359

9. filterfalse

用于创建一个迭代器,该迭代器会返回可迭代对象中不满足指定条件的元素。

filterfalse 函数接受两个参数:

  1. predicate:这是一个函数或者可调用对象,用于定义条件。filterfalse 将会返回可迭代对象中不满足该条件函数的元素。
  2. iterable:这是要从中过滤元素的可迭代对象。
import itertools

data = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def condition(x):
    # 返回偶数
    return x % 2 == 0

# 保留不满足condition的元素
filtered_data = itertools.filterfalse(condition, data)

for item in filtered_data:
    print(item)

image-20240227144213332

10 .groupby

用于根据指定的键对可迭代对象中的元素进行分组。

groupby 函数接受两个参数:

  1. iterable:这是要对其进行分组的可迭代对象。
  2. key (可选):这是一个函数或者可调用对象,用于指定分组的键。如果未提供此参数,groupby 将会将相邻且相等的元素分为一组。

groupby 函数返回一个生成器,该生成器会产生 (key, group) 对,其中 key 是分组的键;group 是对应的元素分组,也是一个可迭代对象。

import itertools

data = ['apple', 'banana', 'orange', 'pear', 'grape', 'kiwi']

# 用len对每个元素进行分组,也就是用字符串的长度进行分组
grouped_data = itertools.groupby(data, key=len)

for key, group in grouped_data:
    print(key)
    print(list(group))

image-20240227145006259

11. islice

用于在可迭代对象中进行切片操作。

islice 函数接受一个或多个参数:

  1. iterable:这是要进行切片操作的可迭代对象。
  2. start:这是切片的起始索引,默认为0。
  3. stop:这是切片的结束索引,但不包括该索引对应的元素。
  4. step:这是切片的步长,默认为1。

islice 函数返回一个迭代器,该迭代器会产生指定范围内的元素。

import itertools

data = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 从下标为2的元素开始,到下标为7的元素结束(不包括下标为7的元素),步长为2
sliced_data = itertools.islice(data, 2, 7, 2)

for item in sliced_data:
    print(item)

image-20240227145353197

12. permutations(排列)

用于生成可迭代对象中所有可能的排列方式。

permutations 函数接受两个参数:

  1. iterable:这是要生成排列的可迭代对象。
  2. r (可选):这是要生成的排列的长度。如果不提供该参数或者为 None,则默认为与输入可迭代对象的长度相同的排列长度。

permutations 函数返回一个迭代器,该迭代器会产生可迭代对象中所有可能的排列方式。

import itertools

data = ['a', 'b', 'c']

permutations = itertools.permutations(data, 2)

# combinatinos必须指定组合的长度
combinations = itertools.combinations(data, 2)

# 排列
for perm in permutations:
    print(perm)
    
print('----------------------------------')

# 组合
for perm in combinations:
    print(perm)

image-20240227145948369

13. product

用于生成可迭代对象中所有可能的笛卡尔积(Cartesian product)。

product 函数接受一个或多个参数。

itertools.product(*iterables, repeat)
  • *iterables 是一个可变参数,用于传入一个或多个可迭代对象。
  • repeat 参数指定了每个输入可迭代对象可以被重复使用的次数,repeat=1表示只能利用一次,repeat=2表示可以利用两次

product 函数返回一个迭代器,该迭代器会产生所有可能的组合,每个组合是来自每个输入可迭代对象的一个元素。

import itertools

# 示例数据
data1 = ['a', 'b', 'c']
data2 = [1, 2]

product_result = itertools.product(data1, data2, repeat=1)

for item in product_result:
    print(item)

image-20240227150627281

14. repeat

itertools.repeat 是一个用于生成指定元素的无限重复的迭代器的函数。

它接受两个参数:

  1. object:要重复的元素。
  2. times (可选):重复的次数,默认为无限重复。
import itertools

repeated_iter = itertools.repeat('hello', 3)

for item in repeated_iter:
    print(item)

image-20240227150758421

15. starmap

用于对可迭代对象中的每个元素应用一个函数,并返回结果(跟map函数很像)。

starmap 函数接受两个参数:

  1. func:这是一个函数,用于对可迭代对象中的每个元素进行处理。
  2. iterable:这是要对其进行处理的可迭代对象,其中每个元素都会作为 func 的参数。

starmap 函数返回一个迭代器,该迭代器会产生 func 对可迭代对象中每个元素处理的结果。

import itertools

data = [(2, 3, 1), (4, 5, 1), (1, 6, 7)]

def add(x, y, z):
    return x + y + z

result = itertools.starmap(add, data)

for item in result:
    print(item)

image-20240227151132379

16. takewhile

用于从可迭代对象中获取满足指定条件的元素,一旦遇到不满足条件的元素,则停止迭代。

takewhile 函数接受两个参数:

  1. predicate:这是一个函数或者可调用对象,用于定义条件。takewhile 将会一直获取可迭代对象中的元素,直到该条件函数返回 False
  2. iterable:这是要从中获取元素的可迭代对象。

takewhile 函数返回一个迭代器,该迭代器会产生满足条件的元素,直到遇到第一个不满足条件的元素。

import itertools

data = [1, 3, 5, 2, 4, 6]

def condition(x):
    return x < 5

result = itertools.takewhile(condition, data)

for item in result:
    print(item)

image-20240227151316790

17. zip_longest

用于将多个可迭代对象中的元素以元组的形式进行配对。

zip_longest 函数接受两个或多个可迭代对象作为参数,并且还可以接受一个 fillvalue 参数,用于指定在输入可迭代对象中某个可迭代对象耗尽时,要使用的填充值。如果不提供 fillvalue 参数,则默认使用 None 进行填充。

import itertools

data1 = ['a', 'b', 'c']
data2 = [1, 2]

zipped_data = itertools.zip_longest(data1, data2, fillvalue='missing')

for item in zipped_data:
    print(item)

image-20240227151645951

  • 20
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值