Python在两个方向上从给定索引开始迭代列表

2024-10-03 11:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来迭代列表oblist,对象从给定的索引x开始。从每次迭代的这个索引中,我想得到两个相邻的元素索引x-1x+1。当一方到达列表的末尾时,迭代不应该停止,但另一方还没有用尽,仍然有元素。在这种情况下,应该为耗尽端返回一个None元素

我试过几种方法来解决这个问题

for element_indexprev, element_indexnext in zip(range(1,len(oblist)), range(-1,len(oblist), - 1)):

但是我没有得到想要的输出。可能也不是最好的方法


Tags: 对象方法innone元素列表forlen
2条回答

你可以用一个简单的例子来解决你的问题

oblist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
start_index = 7

for x in range(len(oblist)):
    x= x+1
    if start_index - x < 0:
        i = None
    else:
        i = oblist[start_index - x]
    if start_index + x > len(oblist) - 1:
        j = None
    else:
        j = oblist[start_index + x]
    if j == None and i == None:
        break
    else:
        print(i , j)

Output
6 8
5 9
4 10
3 11
2 12
1 13
0 14
None 15
None 16

您与zip()很接近,但发现它停在最小列表的末尾

您需要itertools.zip_longest(),文档here

它将拉链拉到最长列表的长度,而不是最短列表的长度。默认情况下,它将使用None填充,但如果需要,可以使用fillvalue参数更改

相关问题 更多 >