gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:10:37 25 4
gpt4 key购买 nike

我正在尝试将一个新元组添加到元组列表(按元组中的第一个元素排序),其中新元组包含列表中前一个元素和下一个元素的元素。

例子:

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() 在特定位置插入,但这并不能真正让我访问下一个元素。

最佳答案

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代替调用 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])

关于python - 根据上一个和下一个元素将元素插入到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38285679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com