python – 根据上一个和下一个元素将元素插入到列表中

前端之家收集整理的这篇文章主要介绍了python – 根据上一个和下一个元素将元素插入到列表中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在元组列表中添加一个新元组(按元组中的第一个元素排序),其中新元组包含列表中上一个元素和下一个元素的元素.

例:

  1. oldList = [(3,10),(4,7),(5,5)]
  2. newList = [(3,5)]

(4,10)由(3,10)和(4,7)之间构建并添加.

  1. Construct (x,y) from (a,y) and (x,b)

我已经尝试使用枚举()插入到特定的位置,但这并不真正让我访问下一个元素.

解决方法

  1. oldList = [(3,5)]
  2.  
  3. def pair(lst):
  4. # create two iterators
  5. it1,it2 = iter(lst),iter(lst)
  6. # move second to the second tuple
  7. next(it2)
  8. for ele in it1:
  9. # yield original
  10. yield ele
  11. # yield first ele from next and first from current
  12. yield (next(it2)[0],ele[1])

哪个会给你:

  1. In [3]: oldList = [(3,5)]
  2.  
  3. In [4]: list(pair(oldList))
  4. Out[4]: [(3,5)]

显然,我们需要做一些错误处理来处理不同的可能情况.

如果您愿意,也可以使用单个迭代器:

  1. def pair(lst):
  2. it = iter(lst)
  3. prev = next(it)
  4. for ele in it:
  5. yield prev
  6. yield (prev[0],ele[1])
  7. prev = ele
  8. yield (prev[0],ele[1])

您可以使用itertools.tee代替调用iter:

  1. from itertools import tee
  2. def pair(lst):
  3. # create two iterators
  4. it1,it2 = tee(lst)
  5. # move second to the second tuple
  6. next(it2)
  7. for ele in it1:
  8. # yield original
  9. yield ele
  10. # yield first ele from next and first from current
  11. yield (next(it2)[0],ele[1])

猜你在找的Python相关文章