[关闭]
@songying 2018-11-13T22:42:42.000000Z 字数 2184 阅读 1135

itertools库

python库


无限迭代器:Infinite iterators

itertools.count(start=0, step=1)

创建一个迭代器,生成从start开始的数,间隔为step,如果超出了sys.maxint,计数器将溢出并继续从-sys.maxint-1开始计算。

  1. def count(start=0, step=1):
  2. # count(10) --> 10 11 12 13 14 ...
  3. # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
  4. n = start
  5. while True:
  6. yield n
  7. n += step

itertools.cycle(iterable)

创建一个迭代器,对iterable中的元素反复执行循环操作,内部会生成iterable中的元素的一个副本,此副本用于返回循环中的重复项。

  1. def cycle(iterable):
  2. # cycle('ABCD') --> A B C D A B C D A B C D ...
  3. saved = []
  4. for element in iterable:
  5. yield element
  6. saved.append(element)
  7. while saved:
  8. for element in saved:
  9. yield element

itertools.repeat(object[, times])

创建一个迭代器,重复生成object,times(如果已提供)指定重复计数,如果未提供times,将无止尽返回该对象。

  1. def repeat(object, times=None):
  2. # repeat(10, 3) --> 10 10 10
  3. if times is None:
  4. while True:
  5. yield object
  6. else:
  7. for i in xrange(times):
  8. yield object

可终止迭代器:Iterators terminating on the shortest input sequence

itertools.chain(*iterables)

将多个迭代器作为参数, 但只返回单个迭代器, 它产生所有参数迭代器的内容, 就好像他们是来自于一个单一的序列.

  1. def chain(*iterables):
  2. # chain('ABC', 'DEF') --> A B C D E F
  3. for it in iterables:
  4. for element in it:
  5. yield element

itertools.compress(data, selectors)

提供一个选择列表,对原始数据进行筛选

  1. def compress(data, selectors):
  2. # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
  3. return (d for d, s in zip(data, selectors) if s)

itertools.dropwhile(predicate, iterable)

创建一个迭代器,只要函数predicate(item)为True,就丢弃iterable中的项,如果predicate返回False,就会生成iterable中的项和所有后续项。
即:在条件为false之后的第一次, 返回迭代器中剩下来的项.

  1. def dropwhile(predicate, iterable):
  2. # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
  3. iterable = iter(iterable)
  4. for x in iterable:
  5. if not predicate(x):
  6. yield x
  7. break
  8. for x in iterable:
  9. yield x

itertools.groupby(iterable[, key])

  1. class groupby:
  2. # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
  3. # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
  4. def __init__(self, iterable, key=None):
  5. if key is None:
  6. key = lambda x: x
  7. self.keyfunc = key
  8. self.it = iter(iterable)
  9. self.tgtkey = self.currkey = self.currvalue = object()
  10. def __iter__(self):
  11. return self
  12. def __next__(self):
  13. self.id = object()
  14. while self.currkey == self.tgtkey:
  15. self.currvalue = next(self.it) # Exit on StopIteration
  16. self.currkey = self.keyfunc(self.currvalue)
  17. self.tgtkey = self.currkey
  18. return (self.currkey, self._grouper(self.tgtkey, self.id))
  19. def _grouper(self, tgtkey, id):
  20. while self.id is id and self.currkey == tgtkey:
  21. yield self.currvalue
  22. try:
  23. self.currvalue = next(self.it)
  24. except StopIteration:
  25. return
  26. self.currkey = self.keyfunc(self.currvalue)

组合迭代器: Combinatoric iterators

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注