Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于上一个和下一个元素将元素插入列表_Python_List - Fatal编程技术网

Python 基于上一个和下一个元素将元素插入列表

Python 基于上一个和下一个元素将元素插入列表,python,list,Python,List,我试图向元组列表中添加一个新元组(按元组中的第一个元素排序),其中新元组包含列表中上一个和下一个元素中的元素 例如: oldList = [(3, 10), (4, 7), (5,5)] newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)] (4,10)由(3,10)和(4,7)构成并添加在两者之间 我曾尝试使用enumerate()在特定位置插入,但这并不能真正让我访问下一个元素 oldList = [(3, 10), (4, 7), (5

我试图向元组列表中添加一个新元组(按元组中的第一个元素排序),其中新元组包含列表中上一个和下一个元素中的元素

例如:

oldList = [(3, 10), (4, 7), (5,5)]
newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
(4,10)由(3,10)和(4,7)构成并添加在两者之间

我曾尝试使用enumerate()在特定位置插入,但这并不能真正让我访问下一个元素

oldList = [(3, 10), (4, 7), (5,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, 10), (4, 7), (5, 5)]

In [4]: list(pair(oldList))
Out[4]: [(3, 10), (4, 10), (4, 7), (5, 7), (5, 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])
您可以使用以下方法代替调用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])

您可以使用列表理解和
itertools.chain()


我本人不是一个单行程序(或复杂性)的狂热爱好者,我将为您的问题提出一个非常明确和可读的(这通常是一件好事!)解决方案

因此,采用非常简单的方法,您可以这样做:

def insertElements(oldList):
    """
    Return a new list, alternating oldList tuples with 
    new tuples in the form (oldList[i+1][0],oldList[i][1])
    """
    newList = []
    for i in range(len(oldList)-1):
      # take one tuple as is
      newList.append(oldList[i])
      # then add a new one with items from current and next tuple
      newList.append((oldList[i+1][0],oldList[i][1]))
    else:
      # don't forget the last tuple
      newList.append(oldList[-1])
    return newList

oldList = [(3, 10), (4, 7), (5, 5)]
newList = insertElements(oldList)
这将在
newList
中为您提供所需的结果:

print(newList)
[(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
<>这比其他更复杂的(和内存有效的)解决方案要长得多,比如使用生成器,我认为读起来比复杂的一行要容易得多。此外,向这个简单函数添加一些检查也很容易(比如确保您有一个元组列表)

除非您已经知道需要优化这段特定的代码(假设这是一个更大的项目的一部分),否则应该这样做。同时它是:易于实现、易于阅读、易于解释、易于维护、易于扩展、易于重构等


注意:在许多方面,前面对您的问题的所有其他答案都比这个简单的答案更好。只是想给你另一个选择。希望这有帮助

用户的输入是什么?新elm的新位置?用户仅提供初始“旧列表”。然后在每两个旧元素之间,在两个现有元素的基础上添加一个新元素。非常感谢,这很有魅力。虽然它适用于我当前的列表,但错误处理将如何改进此方法?@SilviuTofan,实际上就是捕获空/单元组等。。你如何处理它将取决于你想在这种情况下发生什么。谢谢你的回答!我只花了点时间来实现另一个,因为它发布的时间比你的稍早。谢谢你,我也非常感谢这个答案,它使代码变得非常易于阅读和实现!
def insertElements(oldList):
    """
    Return a new list, alternating oldList tuples with 
    new tuples in the form (oldList[i+1][0],oldList[i][1])
    """
    newList = []
    for i in range(len(oldList)-1):
      # take one tuple as is
      newList.append(oldList[i])
      # then add a new one with items from current and next tuple
      newList.append((oldList[i+1][0],oldList[i][1]))
    else:
      # don't forget the last tuple
      newList.append(oldList[-1])
    return newList

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