Python Itertools --- chain,isSlice和izip用示例解释

Itertools is a Python module of functions that return generators, which are objects that only function when iterated over.

Itertools是返回生成器的函数的Python模块,生成器是仅在迭代时起作用的对象。

链() (chain())

The chain() function takes several iterators as arguments. It goes through each element of each passed iterable, then returns a single iterator with the contents of all passed iterators.

chain()函数采用多个迭代器作为参数。 它遍历每个传递的迭代器的每个元素,然后返回具有所有传递的迭代器内容的单个迭代器。

import itertools
list(itertools.chain([1, 2], [3, 4]))

# Output
# [1, 2, 3, 4]

islice() (islice())

The islice() function returns specific elements from the passed iterator.

islice()函数从传递的迭代器返回特定元素。

It takes the same arguments as the slice() operator for lists: start, stop, and step. Start and stop are optional.

对于列表,它采用与slice()运算符相同的参数:开始,停止和步进。 开始和停止是可选的。

import itertools
list(itertools.islice(count(), 5))

# Output
# [0, 1, 2, 3, 4]

izip() (izip())

izip() returns an iterator that combines the elements of the passed iterators into tuples.

izip()返回一个迭代器,该迭代器将传递的迭代器的元素合并为元组。

It works similarly to zip(), but returns an iterator instead of a list.

它的工作方式类似于zip() ,但是返回一个迭代器而不是列表。

import itertools
list(izip([1, 2, 3], ['a', 'b', 'c']))

# Output
# [(1, 'a'),(2, 'b'),(3, 'c')]

更多信息: (More Information:)

翻译自: https://www.freecodecamp.org/news/python-itertools-chain-isslice-and-izip-explained-with-examples/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值