在python中等效长度的zip迭代器

前端之家收集整理的这篇文章主要介绍了在python中等效长度的zip迭代器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果迭代的长度不相等,我正在寻找一种很好的方法来压缩几个迭代,引发异常.

在迭代是列表或具有len方法的情况下,该解决方案是干净和容易的:

  1. def zip_equal(it1,it2):
  2. if len(it1) != len(it2):
  3. raise ValueError("Lengths of iterables are different")
  4. return zip(it1,it2)

但是,如果it1和it2是生成器,则前一个函数失败,因为长度未定义TypeError:类型为“generator”的对象没有len().

我想象,itertools模块提供了一种简单的方法来实现,但到目前为止我还没有找到它.我想出了这个自制的解决方案:

  1. def zip_equal(it1,it2):
  2. exhausted = False
  3. while True:
  4. try:
  5. el1 = next(it1)
  6. if exhausted: # in a prevIoUs iteration it2 was exhausted but it1 still has elements
  7. raise ValueError("it1 and it2 have different lengths")
  8. except StopIteration:
  9. exhausted = True
  10. # it2 must be exhausted too.
  11. try:
  12. el2 = next(it2)
  13. # here it2 is not exhausted.
  14. if exhausted: # it1 was exhausted => raise
  15. raise ValueError("it1 and it2 have different lengths")
  16. except StopIteration:
  17. # here it2 is exhausted
  18. if not exhausted:
  19. # but it1 was not exhausted => raise
  20. raise ValueError("it1 and it2 have different lengths")
  21. exhausted = True
  22. if not exhausted:
  23. yield (el1,el2)
  24. else:
  25. return

解决方案可以用以下代码进行测试:

  1. it1 = (x for x in ['a','b','c']) # it1 has length 3
  2. it2 = (x for x in [0,1,2,3]) # it2 has length 4
  3. list(zip_equal(it1,it2)) # len(it1) < len(it2) => raise
  4. it1 = (x for x in ['a',3]) # it2 has length 4
  5. list(zip_equal(it2,it1)) # len(it2) > len(it1) => raise
  6. it1 = (x for x in ['a','c','d']) # it1 has length 4
  7. it2 = (x for x in [0,3]) # it2 has length 4
  8. list(zip_equal(it1,it2)) # like zip (or izip in python2)

我是否俯视任何替代解决方案?我的zip_equal函数有更简单的实现吗?

PS:我在Python 3中写了这个问题,但Python 2解决方案也是受欢迎的.

解决方法

我可以使用itertools.zip_longest()并使用itertools.zip_longest()引发异常,如果用于填充较短的迭代的sentinel值存在于生成的元组中:
  1. from itertools import zip_longest
  2.  
  3. def zip_equal(*iterables):
  4. sentinel = object()
  5. for combo in zip_longest(*iterables,fillvalue=sentinel):
  6. if sentinel in combo:
  7. raise ValueError('Iterables have different lengths')
  8. yield combo

不幸的是,我们不能使用带有yield的zip()来避免Python代码循环,每次迭代都要进行测试;一旦最短的迭代器用尽,zip()将推进所有以前的迭代器,从而吞噬证据,如果那些中只有一个额外的项目.

猜你在找的Python相关文章