📜  Python|列表中的连续元素配对(1)

📅  最后修改于: 2023-12-03 15:19:18.491000             🧑  作者: Mango

Python | 列表中的连续元素配对

在Python中,我们可以使用以下方法将列表中的连续元素组成一对:

from itertools import tee

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

此函数将返回一个生成器对象,其中每个元素对其相邻元素进行配对。例如,对于以下列表:

lst = [1, 2, 3, 4, 5]

我们可以使用此函数将连续元素进行配对:

pairwise(lst)
# 输出
# [(1, 2), (2, 3), (3, 4), (4, 5)]

这个函数也适用于字符串列表。例如:

lst = ["apple", "banana", "cherry", "date", "fig"]
pairwise(lst)
# 输出
# [('apple', 'banana'), ('banana', 'cherry'), ('cherry', 'date'), ('date', 'fig')]

这对于处理大量的时间序列、坐标对和其他相邻的数据点非常有用。