Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(Python)列表索引超出范围错误_Python - Fatal编程技术网

(Python)列表索引超出范围错误

(Python)列表索引超出范围错误,python,Python,此函数在第8行返回ListIndex错误。我尝试计算nList中所有平方值的总和: def oneVolume(n): j = 0 Sum = 0 nList = [] for i in range (n): nList.append(2*random()-1) while j <= n: Sum = Sum +nList[j] # line with list index error j = j+1 return Sum de

此函数在第8行返回ListIndex错误。我尝试计算nList中所有平方值的总和:

def oneVolume(n):
  j = 0
  Sum = 0
  nList = []
  for i in range (n):
    nList.append(2*random()-1)
    while j <= n:
      Sum = Sum +nList[j] # line with list index error
      j = j+1
  return Sum
def oneVolume(n):
j=0
总和=0
nList=[]
对于范围(n)中的i:
nList.append(2*random()-1)

当j时,有一个off by 1错误

l = []
l.append(1)
l.append(2)
l.append(3)
我会考虑三个要素。它们将是l[0](包含0)、l[1]和l[2]

len(l)将是3岁

引用l[3]将是一个超出范围的索引

while j <= n:

但您可以使用生成器和内置的求和函数进一步简化:

def oneVolume(n):
    return sum(2*random()-1 for _ in range(n))

生成器非常类似于一个列表,
[2*random()-1表示uuin range(n)]
,只是更短暂。这将被传递到
求和
,它会自动执行函数后半部分所需的操作。

您是否正在尝试
求和
?尝试
sum(nList)
。我想对列表中的每个值求平方,然后对所有的平方进行求和values@user3349164
sum([x**2代表nList中的x])
@user3349164或与@loki类似的风格,
sum(map(lambda x:x**2,nList))
def oneVolume(n):
    Sum = 0
    nList = []
    for i in range(n):
        nList.append(2*random()-1)
    for j in nList:
        Sum = Sum + j
    return Sum
def oneVolume(n):
    return sum(2*random()-1 for _ in range(n))