我试图将新元组添加到元组列表中(按元组中的第一个元素排序),其中新元组包含列表中前一个元素和下一个元素的元素。
示例:
oldList = [(3, 10), (4, 7), (5,5)]
newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
(4,10)由(3, 10 )和( 4 ,7)构建并添加。
Construct (x,y) from (a,y) and (x,b)
我尝试使用enumerate()插入特定位置,但这并不能让我访问下一个元素。
答案 0 :(得分:8)
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])
您可以使用itertools.tee代替调用它:
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])
答案 1 :(得分:5)
您可以使用列表推导和itertools.chain()
:
>>> list(chain.from_iterable([((i, j), (x, j)) for (i, j), (x, y) in zip(oldList, oldList[1:])])) + oldList[-1:]
[(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)]
答案 2 :(得分:3)
我自己不是单行(或复杂性)的忠实粉丝,我会提出一个非常明确和可读(通常是一件好事!)解决问题的方法。
所以,采用非常简单的方法,你可以这样做:
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)]
这不是比其他更复杂(和内存效率高!)解决方案更长的代码,比如使用生成器,我认为它比复杂的单行程更容易阅读。此外,很容易为这个简单的函数添加一些检查(比如确保你有一个元组列表)。
除非您已经知道需要优化代码的这一特定部分(假设这是一个更大的项目的一部分),这应该是good enough。同时它具有:易于实现,易于阅读,易于解释,易于维护,易于扩展,易于重构等。
注意:在很多方面,您问题的所有其他先前答案也是比这个简单更好的解决方案。只是想给你另一个选择。希望这可以帮助。