简体   繁体   English

IndexError:索引超出范围:5

[英]IndexError: index out of range: 5

So I am in an intro programming class and I have an assignment where I need to take in a list as a param, and then return a list with only the vals from the first list that are divisible by 6. The class uses Python and this is what I think should be working but I keep getting an error. 因此,我在一个入门编程类中,我有一个分配,需要在其中添加一个列表作为参数,然后返回一个列表,其中仅包含第一个列表中可被6整除的值。该类使用Python,是我认为应该正常工作的内容,但我一直遇到错误。

    def youAndThe6th(nums):
        numsNew =  []
        for x in nums:
            if nums[x]%6 ==0:
                numsNew.append(nums[x])
        return numsNew

And then when I run something like: 然后当我运行类似的东西时:

     youAndThe6th([1,2,3,4])

I get and error saying "IndexError: index out of range: 4". 我收到错误提示“ IndexError:索引超出范围:4”。 And the 4 is just 1 plus the last index. 而4只是1加最后一个索引。 So I understand that it is trying to check and index that isn't in the list, I just don't see what about my code is trying to call past the last index of the given string. 因此,我知道它正在尝试检查和索引不在列表中的内容,只是看不到我的代码正在尝试调用给定字符串的最后一个索引。

Thanks! 谢谢!

First thing first python list are zero indexed that is they start from 0 首先,第一个python列表的索引为零,即它们从0开始

Modified Code: 修改后的代码:

def youAndThe6th(nums):
    numsNew =  []
    for x in nums:
        if x%6 ==0:
            numsNew.append(x)
    return numsNew

Modified code with range: 修改后的代码范围:

def youAndThe6th(nums):
    numsNew =  []
    for x in range(len(nums)):
        if x%6 ==0:
            numsNew.append(x)
    return numsNew

or we could make things easier in my point of view using list comprehension 或者我们可以使用列表理解使事情变得更容易

numsNew =[x for x in nums if x%6 == 0]

Notes: 笔记:

  • When you loop through an list you are actually looping over it's content and not it's index you could use range if you want it's index 当您遍历一个列表时,实际上是遍历它的内容而不是它的索引,如果希望它是索引,则可以使用范围
  • Your list has four elements values = [ 1 , 2 , 3 , 4] index = 0 , 1 , 2 , 3 So when you were iterating over the list you got the value 4 and you did nums[x] == nums[4] since the list has only index up to 3 it throw IndexError: index out of range: 4 您的列表具有四个元素values = [ 1 , 2 , 3 , 4] index = 0 , 1 , 2 , 3因此,当您遍历列表时,得到的值是4并且执行了nums[x] == nums[4]因为列表只有最多3个索引,所以它抛出IndexError: index out of range: 4

Your problem is in line 4. Instead of 您的问题在第4行。

if nums[x]%6 == 0:

you ought to have 你应该有

if x%6 == 0:

What's happening is that your for statement is already giving you the values stored in the list (as x). 发生的情况是您的for语句已经为您提供了存储在列表中的值(以x表示)。 You're then trying to take the xth value of the list, and in your case, your list only has 4 values, so asking for value 4 is out of range (since python starts counting with 0). 然后,您尝试获取列表的第x个值,在您的情况下,您的列表仅包含4个值,因此要求值4超出范围(因为python从0开始计数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM