获取索引函数错误

时间:2014-05-14 20:04:49

标签: python python-3.x

def doubles(lst):
    for i in range(len(lst)):
        if lst[i]*2==lst[i+1]:
            print(lst[i+1],end=' ')

我得到了什么:

8 -24 6 12 24 Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    doubles( [4,8,-12,-24,48,3,6,12,24,2])
    line 32, in doubles
    if lst[i+1]:
IndexError: list index out of range

输出是我想要的8 -24 6 12 24,但我不知道如何摆脱此函数的索引错误。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

循环直到一个但最后一个元素

def doubles(lst):
    for i in range(len(lst) - 1):
        if lst[i] * 2 == lst[i + 1]:
            print(lst[i + 1], end=' ')

因为否则你试图访问lst[i + 1],保证比列表中的元素更进一步的索引。

您还可以直接在lst上与enumerate()一起循环以生成索引:

def doubles(lst):
    for i, elem in enumerate(lst[:-1]):
        if elem * 2 == lst[i + 1]:
            print(lst[i + 1], end=' ')

或者您可以使用zip()将元素与下一个元素配对:

def doubles(lst):
    for i, j in zip(lst, lst[1:]):
        if i * 2 == j:
            print(j, end=' ')

你可以将它放入生成器表达式中:

def doubles(lst):
    print(*(j for i, j in zip(lst, lst[1:]) if i * 2 == j), sep=' ')

所有这些的演示:

>>> [4,8,-12,-24,48,3,6,12,24,2]
[4, 8, -12, -24, 48, 3, 6, 12, 24, 2]
>>> lst = [4,8,-12,-24,48,3,6,12,24,2]
>>> for i in range(len(lst) - 1):
...     if lst[i] * 2 == lst[i + 1]:
...         print(lst[i + 1], end=' ')
... 
8 -24 6 12 24 >>> 
>>> for i, elem in enumerate(lst[:-1]):
...     if elem * 2 == lst[i + 1]:
...         print(lst[i + 1], end=' ')
... 
8 -24 6 12 24 >>> 
>>> for i, j in zip(lst, lst[1:]):
...     if i * 2 == j:
...         print(j, end=' ')
... 
8 -24 6 12 24 >>> 
>>> print(*(j for i, j in zip(lst, lst[1:]) if i * 2 == j), sep=' ')
8 -24 6 12 24

答案 1 :(得分:0)

您可以使用itertools docs中的pairwise食谱:

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def doubles(lst):    
    for x,y in pairwise(lst):
        if x * 2 == y:
            print(y, end=' ')
相关问题