首页 经验

python itertools模块

时间: 2024-04-27 14:38:34

(部分内容来自网络,其真实性存疑,为了避免对您造成误导,请谨慎甄别。)


itertools 是 Python 的一个内置模块,它提供了一些快速、内存有效的工具来处理迭代器。迭代器是 Python 中可以记住遍历的位置的对象,它可以从头到尾访问数据集合的元素。itertools 模块中的函数通常用于处理迭代器,生成迭代器,或者组合迭代器的元素。

以下是一些 itertools 模块中常用的函数:

  1. chain(): 将多个迭代器链接成一个迭代器。

import itertools  
  
list(itertools.chain([1, 2, 3], [4, 5, 6]))  # 输出: [1, 2, 3, 4, 5, 6]
  1. count(): 创建一个迭代器,生成从指定的起始值开始的连续整数。

count_from_three = itertools.count(3)  
print(next(count_from_three))  # 输出: 3  
print(next(count_from_three))  # 输出: 4
  1. cycle(): 创建一个迭代器,重复元素无限次。

cycle_ab = itertools.cycle('ab')  
print(next(cycle_ab))  # 输出: 'a'  
print(next(cycle_ab))  # 输出: 'b'
  1. dropwhile(): 创建一个迭代器,从迭代器中删除满足指定条件的元素,直到条件不再满足。

is_less_than_three = lambda x: x < 3  
drop_less_than_three = itertools.dropwhile(is_less_than_three, [1, 2, 3, 4, 5])  
print(list(drop_less_than_three))  # 输出: [3, 4, 5]
  1. groupby(): 创建一个迭代器,它将连续的元素分组,这些元素具有相同的键(由提供的函数产生)。

is_even = lambda x: x % 2 == 0  
grouped = itertools.groupby([1, 2, 2, 3, 3, 3, 4, 4], is_even)  
for key, group in grouped:  
    print(key, list(group))  
# 输出:  
# False [1]  
# True [2, 2]  
# False [3, 3, 3]  
# True [4, 4]
  1. product(): 计算笛卡尔积。

print(list(itertools.product([1, 2], ['a', 'b'])))  
# 输出: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
  1. permutations(): 返回一个迭代器,产生输入元素的排列。

print(list(itertools.permutations([1, 2, 3])))  
# 输出: [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 2, 1), (3, 1, 2)]
  1. combinations(): 返回一个迭代器,产生输入元素的组合。

print(list(itertools.combinations([1, 2, 3], 2)))  
# 输出: [(1, 2), (1, 3), (2, 3)]

这只是 itertools 模块提供的功能的冰山一角。模块中还有许多其他函数和工具,可以帮助你更有效地处理数据。


上一个 python collections模块 文章列表 下一个 新西兰多大

最新

工具

© 2019-至今 适观科技

沪ICP备17002269号