2015-11-10 22 views
4

的任务是让用户输入4个数字,然后将它们存储在一个文本文件,打开文本文件,展示了在不同线路的4个数字,然后得到这些数字的平均值并将其显示给用户。 这里是我到目前为止的代码:Python列表索引加载列表中未发现从文本文件

__author__ = 'Luca Sorrentino' 


numbers = open("Numbers", 'r+') 
numbers.truncate() #OPENS THE FILE AND DELETES THE PREVIOUS CONTENT 
        # Otherwise it prints out all the inputs into the file ever 

numbers = open("Numbers", 'a') #Opens the file so that it can be added to 
liist = list() #Creates a list called liist 

def entry(): #Defines a function called entry, to enable the user to enter numbers 
     try: 
      inputt = float(input("Please enter a number")) #Stores the users input as a float in a variable 
      liist.append(inputt) #Appends the input into liist 
     except ValueError: #Error catching that loops until input is correct 
      print("Please try again. Ensure your input is a valid number in numerical form") 
      entry() #Runs entry function again to enable the user to retry. 

x = 0 
while x < 4: # While loop so that the program collects 4 numbers 
    entry() 
    x = x + 1 

for inputt in liist: 
    numbers.write("%s\n" % inputt) #Writes liist into the text file 


numbers.close() #Closes the file 

numbers = open("Numbers", 'r+') 

output = (numbers.readlines()) 

my_list = list() 
my_list.append(output) 

print(my_list) 
print(my_list[1]) 

问题是装载数从文本文件回来,然后存储每一个作为变量,这样我可以让他们的平均值。 我似乎无法找到一种方法来明确定位每个数字,只是每个字节不是我想要的。

+1

取出括号你的'readlines'功能,只是尝试'打印(输出)':你应该看到一个你的号码列表。 –

+0

除了'print(my_list)'的错误输出和'print(my_list [1])的崩溃',这个代码还有其他一些问题。一旦你得到它的工作,我鼓励你问一个关于[codereview.se]的问题。 –

+1

题外话:你的档案管理真的很差。你用“r +”打开文件只是截断(不是实际读取),然后(不关闭)重新打开追加,然后重新打开“r +”(这次读取,但不写入,所以+是毫无意义的)。只需打开一次“w +”,它可以让你读取和写入,并为你截断文件。当你完成写作(填充文件)时,你可以'回到开始读取它。您也可以切换到'with'语句来管理文件对象的生存期。 – ShadowRanger

回答

2

您将有两个主要问题。

首先,.append()用于将个人项目添加到列表,而不是用于将一个列表添加到另一个列表。因为您使用的是.append(),所以您最终列出了包含一个项目的列表,并且该项目本身就是一个列表...不是您想要的,以及对错误消息的解释。将一个列表连接到另一个列表.extend()+=可以工作,但是您应该问自己,对于您的情况来说这是否是必要的。

其次,你的列表元素是字符串,你想与他们的数字工作。 float()会将它们转换为你。

在一般情况下,你应该调查“列表内涵”的概念。他们使这样的操作非常方便。下面的示例创建一个新的列表,其成员是你.readlines()输出分别float()版版本:

my_list = [float(x) for x in output] 

添加条件语句到一个列表理解的能力也是一个真正复杂的金丹。例如,如果你想跳过已悄悄进入你的文件中的任何空/空白行:

my_list = [float(x) for x in output if len(x.strip())] 
3

你的列表(my_list)只有1个项目 - 与您想要的物品清单。

你可以看到这一点,如果你尝试打印(LEN(my_list)),所以您的打印(my_list [1]),超出的范围,因为具有指数= 1的项目不存在。

当你创建一个空的列表,并添加,要添加一个项目到列表中,这是可变输出有效,对于一个值输出。

为了得到你想要的只是做

my_list = list(output) 
1

你可以改变你的程序一点点的结束,它会工作:

output = numbers.readlines() 
# this line uses a list comprehension to make 
# a new list without new lines 
output = [i.strip() for i in output] 
for num in output: 
    print(num) 
1.0 
2.0 
3.0 
4.0 

print sum(float(i) for i in output) 
10