簡體   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