繁体   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)

我得到了这个错误:

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

我相信您想这样做:(对您的代码稍作修改)

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

这会迭代列表 b 的长度,即 [0, 1, 2] 为 len(b) = 3。这些是列表 a 的有效索引。

在上述实现中,您正在迭代的列表是 [1, 1, 5]。 并且 a[5] 不存在,因为列表 a 只有 4 个元素。

希望这可以帮助!

你得到这个错误的原因是你的列表b有数字5并且你的列表a的长度为 5,因此最大索引为 4,因为索引从 0 开始。

因此,当您尝试从索引5处的列表a中获取值时,没有这样的值会导致错误: list index out of range

暂无
暂无

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

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