简体   繁体   English

为什么我会收到此 IndexError

[英]Why am I getting this IndexError

a = [1,2,1,5]

b = [1,1,5]

c = [a[index] for index in b]  
print(c)

and I got this error:我得到了这个错误:

IndexError
Traceback (most recent call last)
<ipython-input-158-e03093b57c86> in <module>

    2 b=[1,1,5]
      3 index=0
----> 4 c=[a[index] for index in b]
      5 c

<ipython-input-158-e03093b57c86> in <listcomp>(.0)

    2 b=[1,1,5]
      3 index=0
----> 4 c=[a[index] for index in b]
      5 c

IndexError: list index out of range

I believe you wanted to do this: (Slight modification of your code)我相信您想这样做:(对您的代码稍作修改)

c = [a[index] for index in range(len(b))]

This iterates over the length of list b, which is [0, 1, 2] as len(b) = 3. And these are valid indexes for list a.这会迭代列表 b 的长度,即 [0, 1, 2] 为 len(b) = 3。这些是列表 a 的有效索引。

In the above implemenation, the list you are iterating over is [1, 1, 5].在上述实现中,您正在迭代的列表是 [1, 1, 5]。 And a[5] does not exist since list a has only 4 elements.并且 a[5] 不存在,因为列表 a 只有 4 个元素。

Hope this helps!希望这可以帮助!

The reason you are getting this is error is because your list b has got the number 5 and your list a is of length 5 and hence has a maximum index of 4, since indexing starts from 0.你得到这个错误的原因是你的列表b有数字5并且你的列表a的长度为 5,因此最大索引为 4,因为索引从 0 开始。

So when you try and grab the value from list a at index 5 , there is no such value which results in the error: list index out of range因此,当您尝试从索引5处的列表a中获取值时,没有这样的值会导致错误: list index out of range

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

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