Python元素迭代器

最近更新時間 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')]
rss_feed