我正在寻找一种方法来迭代列表oblist
,对象从给定的索引x
开始。从每次迭代的这个索引中,我想得到两个相邻的元素索引x-1
和x+1
。当一方到达列表的末尾时,迭代不应该停止,但另一方还没有用尽,仍然有元素。在这种情况下,应该为耗尽端返回一个None
元素
我试过几种方法来解决这个问题
for element_indexprev, element_indexnext in zip(range(1,len(oblist)), range(-1,len(oblist), - 1)):
但是我没有得到想要的输出。可能也不是最好的方法
Tags:
你可以用一个简单的例子来解决你的问题
您与
zip()
很接近,但发现它停在最小列表的末尾您需要
itertools.zip_longest()
,文档here它将拉链拉到最长列表的长度,而不是最短列表的长度。默认情况下,它将使用
None
填充,但如果需要,可以使用fillvalue
参数更改相关问题 更多 >
编程相关推荐