算法:IndexError:列表索引超出范围(Python) [英] Algorithm: IndexError: list index out of range (Python)
问题描述
我是 Python 新手,我想知道为什么我的程序在第 4 行显示IndexError: list index out of range".任何人都可以帮忙.
I'm new to python and I wanted to know why my program is displaying "IndexError: list index out of range" for line 4. Can anyone please help.
# A is the array and N is the size of the array.
A =[1,78,46,4,34,10,50,2]
N = len(A)
def Algorithm(A,N):
#B <- Array[N]
B = A[N]
B=[0]*N
for i in range(1,N):
B[A[i]]+=1
i=1
#for i <-- 1 to N
for j in range(1,N):
#for k <-- to B[j]
for k in range(0,B[j]):
A[i]=j
i+=1
return
Algorithm(A,N)
print(A)
错误:
2 N = len(A)
3 def Algorithm(A,N):
4 B = A[N]
5 B=[0]*N
6 for i in range(1,N):
IndexError: 列表索引超出范围
IndexError: list index out of range
推荐答案
所以 List index out of range
来自 B = A[N]
因为 N 代表A 的总长度但是,列表元素的索引从 0 到 N-1,这为您提供了长度 (N-1) - 0 + 1 =>否
.如果要将 B
分配给 A
的最后一个元素,可以通过 B = A[N-1]
或 B = A[-1]
,因为负索引从末尾指向列表的元素.但是,如果您重新声明 B = [0] * N
,您可以取消第一个赋值
So the List index out of range
comes from B = A[N]
because N represents the total length of A.
However, elements of a list are indexed from 0 up to N-1, which gives you the length (N-1) - 0 + 1 => N
. If you want to assign B
to the last element of A
, you can do that by B = A[N-1]
, or B = A[-1]
, since negative indices point to elements of the list from the end. However, given you redeclare B = [0] * N
, you could do away with the first assignment
这篇关于算法:IndexError:列表索引超出范围(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!