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

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

例:

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

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

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

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

解决方法

oldList = [(3,5)]

def pair(lst):
    # create two iterators
    it1,it2 = iter(lst),iter(lst)
    # move second to the second tuple
    next(it2)
    for ele in it1:
        # yield original
        yield ele
        # yield first ele from next and first from current
        yield (next(it2)[0],ele[1])

哪个会给你:

In [3]: oldList = [(3,5)]

In [4]: list(pair(oldList))
Out[4]: [(3,5)]

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

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

def pair(lst):
    it = iter(lst)
    prev = next(it)
    for ele in it:
        yield prev
        yield (prev[0],ele[1])
        prev = ele
    yield (prev[0],ele[1])

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

from itertools import tee
def pair(lst):
    # create two iterators
    it1,it2 = tee(lst)
    # move second to the second tuple
    next(it2)
    for ele in it1:
        # yield original
        yield ele
        # yield first ele from next and first from current
        yield (next(it2)[0],ele[1])
原文链接:https://www.f2er.com/python/185861.html

猜你在找的Python相关文章