Python元素迭代器

Lasted 2020-01-21 13:22:16

当同时在两个或更多序列中循环时,可以用 zip() 函数将其内元素一一匹配。

创建一个聚合了来自每个可迭代对象中的元素的迭代器。

函数定义

def zip(*iterables):
  # zip('ABCD', 'xy') --> Ax By
  sentinel = object()
  iterators = [iter(it) for it in iterables]
  while iterators:
    result = []
    for it in iterators:
      elem = next(it, sentinel)
      if elem is sentinel:
        return
      result.append(elem)
    yield tuple(result)

示例

questions = ['name', 'quest', 'color']
answers = ['Mike', 'the grail', 'blue']
for q, a in zip(questions, answers):
  print('Q:{0}? A:{1}.'.format(q, a))
Q:name? A:Mike.
Q:quest? A:the grail.
Q:color? A:blue.
注意:函数从左至右进行匹配,如果元素不匹配不会返回元素。

多个对象合并。

x = ['IBM', 'Apple', 'Google']
y = [138.31, 318.73, 1479.52]
z = ['I', 'A', 'G']
zipped = zip(x, y, z)
print(list(zipped))
[('IBM', 138.31, 'I'), ('Apple', 318.73, 'A'), ('Google', 1479.52, 'G')]