Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取函数的索引错误_Python_Python 3.x - Fatal编程技术网

Python 获取函数的索引错误

Python 获取函数的索引错误,python,python-3.x,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回溯(最近一次呼叫最后一次): 文件“”,第1行,在 双打([4,8,-12,-24,48,3,6,12,24,2]) 第32排,双打 如果lst[i+1]: 索引器:列表索引超出范围 输出是我想要的8-24 6 12 24,但

我得到的是:

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回溯(最近一次呼叫最后一次):
文件“”,第1行,在
双打([4,8,-12,-24,48,3,6,12,24,2])
第32排,双打
如果lst[i+1]:
索引器:列表索引超出范围
输出是我想要的
8-24 6 12 24
,但我不确定如何消除此函数的索引错误。有什么想法吗?

循环直到最后一个元素:

def doubles(lst):
    for i, elem in enumerate(lst[:-1]):
        if elem * 2 == lst[i + 1]:
            print(lst[i + 1], end=' ')
因为否则您将尝试访问
lst[i+1]
,它保证比列表中的元素多1个索引

您还可以直接在
lst
上循环,并使用
enumerate()
生成索引:

def doubles(lst):
    for i in range(len(lst) - 1):
        if lst[i] * 2 == lst[i + 1]:
            print(lst[i + 1], end=' ')
或者可以使用
zip()
将元素与下一个元素配对:

def doubles(lst):
    for i, elem in enumerate(lst[:-1]):
        if elem * 2 == lst[i + 1]:
            print(lst[i + 1], end=' ')
可以将其放入生成器表达式中:

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
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=' ')