如何获取 Python 列表的切片以获得连续元素的组合?

How to get slices of Python list to get combination of consecutive elements?

假设我有一个列表

l = ['p4', 'p6', 'p7', 'p9']

我想得到这样的输出 [['p4', 'p6'], ['p6', 'p7'], ['p7', 'p9']] ,顺序是必须的(我不想要元素的组合)。Python 中是否有一个函数可以做到这一点?

要获得一对连续的元素,使用zip

>>> list(zip(l, l[1:]))
[('p4', 'p6'), ('p6', 'p7'), ('p7', 'p9')]

要将所有内部元素都作为列表,请使用 map

>>> list(map(list, zip(l, l[1:])))
[['p4', 'p6'], ['p6', 'p7'], ['p7', 'p9']]
l = ['p4', 'p6', 'p7', 'p8', 'p9']
finalList = []

for i in range(0, len(l)-1):
    tempList = [l[i], l[i+1]]
    finalList.append(tempList)

print(finalList)

>> [['p4', 'p6'], ['p6', 'p7'], ['p7', 'p8'], ['p8', 'p9']]