真奇怪的Python

2024-04-27 01:12:05 发布

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

...
def splitMunipulation(p,threshold=5000):
    runs=[];i=0
    while i<len(p):
        l=[];i+=1
        print i,p[i]
        while p[i]!=press(0,1,0):
            l.append(p[i]);i+=1
        else:       
            runs.append(l)#here i points to another (0,1,0)
    return runs
...

record=splitMunipulation(record)

''

输出:

    1 <__main__.press instance at 0x046690A8>
      File "H:\mutate.py", line 28, in splitMunipulation
        while p[i]!=press(0,1,0):
    IndexError: list index out of range

press是一个类

既然print p[i]运行良好,为什么p[i]被认为超出了范围?你知道吗

真的不明白发生了什么

''


Tags: tothresholdlenheredefanotherrunsrecord
3条回答
while p[i]!=press(0,1,0):
   l.append(p[i]);i+=1

变量i在此循环中递增,直到p[i]!=press(0,1,0)。由于没有发生任何事情使p变长,或者测试i不大于p的长度,因此很容易看出索引如何超出范围。你知道吗

len返回长度,而不是最后一个索引。如果l=[1,2,3],那么len(l)返回3,但l[3]超出范围。你知道吗

所以你应该用

while i<len(p)-1

或者更好:

for i in range(len(p)):

所以,有几件事。。你知道吗

首先,你的代码非常。。。非音速的。这不是C语言,所以在Python中不需要使用while循环进行迭代,也不需要使用分号来分隔一行中的多个命令。永远不会。另外,whileelse格式很容易混淆,应该避免使用。你知道吗

如果您查看while循环的前几行

while i<len(p):
        l=[];i+=1

i保持在p长度以下,但立即将i的值增加1。因此,当i=len(p) - 1时,您将使i变大len(p)。因此,当您试图访问p[i]时,您试图访问的是一个不存在的值。你知道吗

解决这些问题,您将得到:

...
def splitMunipulation(p,threshold=5000):
    runs=[]

    for i in p:
        l=[]
        print i
        if i != press(0,1,0):
            runs.append(i)
    return runs
...

record=splitMunipulation(record)

相关问题 更多 >