gpt4 book ai didi

python - 在 python 中将列表分解为重叠的元组列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:27 25 4
gpt4 key购买 nike

假设我有:

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)

最佳答案

您可以使用 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)]
>>>

关于python - 在 python 中将列表分解为重叠的元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23507320/

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