2017-07-22 42 views
-1

我想创建一个简单的数组程序并打印出数组元素,但在我输入员工2的值后说:IndexError:list assignment index out of range。列表分配索引超出范围错误

#Create constant for the number of employees. 
SIZE = 3 

#Create an array to hol the number of hours worked by each employee. 
hours = [SIZE] 

#Get the hours worked by employee 1. 
hours[0] = int(input("Enter the hours worked by employee 1: ")) 

#Get the hours worked by employee 2. 
hours[1] = int(input("Enter the hours worked by employee 2: ")) 

#Get the hours worked by employee 3. 
hours[2] = int(input("Enter the hours worked by employee 3: ")) 

#Display the values entered. 
print("The hours you entered are:") 
print(hours[0]) 
print(hours[1]) 
print(hours[2]) 
+1

你没有设置任何尺寸的小时= [SIZE],你的列表只有一个索引 – PRMoureu

+0

'[SIZE]'是一个1元素的列表,其唯一的元素是3号。 – user2357112

回答

0

值Python没有字面数组:它有名单。 hours = [SIZE]不会创建包含3个元素的列表:它会创建一个包含1个元素的列表。您应该使用append()将项目添加到列表中,而不是索引超过数组末尾。

正确的代码看起来像这样的元素添加到列表:

hours.append(int(input("Enter the hours worked by employee 1: "))) 
hours.append(int(input("Enter the hours worked by employee 2: "))) 
hours.append(int(input("Enter the hours worked by employee 3: "))) 

从评论,似乎你正在学习从伪教科书代码:这是美妙的。请记住,虽然某些常用于伪代码的惯例,或者有时类似于C语言的惯例在其他编程语言中可能会有所不同。例如,在C中,这声明了一个名为x的50个字符的数组。

char x[50]; 

在Python中,不能使用相同的语法。祝你好运。

+1

谢谢。我正在学习编程逻辑,他们使用伪代码,我正在尝试将其转换为Python代码。 – Cornel

+1

Python实际上的确拥有数组https://docs.python.org/3/library/array.html –

+0

@ cricket_007是的,我知道,NumPy的确是基于它们的。但不是文字数组。我应该提到这一点。谢谢。 –

0

您似乎对如何在Python中使用数组工作有错误的想法。本质上讲,当你键入

#Create constant for the number of employees. 
SIZE = 3 

#Create an array to hol the number of hours worked by each employee. 
hours = [SIZE] 

你在做什么是创建一个元素的数组的3

hours = [3] 
相关问题