将列表分成python中重叠的元组列表

时间:2014-05-07 01:44:31

标签: python

说我有:

path1 = [0,3,1]
path2 = [0, 3, 2, 1]

我想要

splitsOfPath1 = [(0,3), (3,1)]
splitsOfPath2 = [(0,3), (3, 2), (2, 1)]

如何实现这一目标?我读取路径的方式是从0到1,你需要访问3.但要打破它,从0到1。你需要从0到3(0,3)然后从3到1(3,1)

1 个答案:

答案 0 :(得分:5)

您可以使用zipExplain Python's slice notation

>>> path1 = [0, 3, 1]
>>> splitsOfPath1 = zip(path1, path1[1::])
>>> splitsOfPath1
[(0, 3), (3, 1)]
>>>
>>> path2 = [0, 3, 2, 1]
>>> splitsOfPath2 = zip(path2, path2[1::])
>>> splitsOfPath2
[(0, 3), (3, 2), (2, 1)]
>>>