python – 根据上一个和下一个元素将元素插入到列表中
发布时间:2020-11-17 23:08:00 所属栏目:Python 来源:互联网
导读:我试图在元组列表中添加一个新元组(按元组中的第一个元素排序),其中新元组包含列表中上一个元素和下一个元素的元素. 例: oldList = [(3, 10), (4, 7), (5,5)]newList = [(3, 10), (4, 10), (4, 7), (5, 7), (5, 5)] (4,10)由(3,10)和(4,7)之间构建并添加. Co
|
我试图在元组列表中添加一个新元组(按元组中的第一个元素排序),其中新元组包含列表中上一个元素和下一个元素的元素. 例: 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]) (编辑:哈尔滨站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
