从文本文件加载列表时,Python列表索引未找到。

4

任务是让用户输入4个数字,然后将它们存储在一个文本文件中,打开该文本文件,在不同的行上显示这4个数字,然后计算这些数字的平均值并向用户显示。

以下是我目前的代码:

__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函数周围的括号,只尝试使用print(output):你应该能看到一个数字列表。 - R Nar
除了 print(my_list) 的错误输出和在 print(my_list[1]) 处崩溃之外,这段代码还存在其他问题。一旦你让它正常工作,我鼓励你在 [codereview.se] 上提出问题。 - 200_success
1
离题:你的文件管理真的很差。你只是用“r+”打开文件一次来截断(实际上没有读取),然后(没有关闭)重新打开进行追加,然后稍后重新打开为“r+”(这次读取,但不写入,所以+是无意义的)。只需一次使用“w+”打开它,这将让您既可以读取又可以写入,并截断文件。当您完成写入(以填充文件)时,可以seek回到开头进行读取。您还可以切换到with语句以管理文件对象的生命周期。 - ShadowRanger
@ShadowRanger 你好,谢谢。我已经用“w”替换了所有不同格式的开头,它可以工作,但我不确定如何让它回到开头?谢谢。 - mrzippy01
@lucafsorrentino:既然您需要读写(且要截断),您应该使用模式w+。有关寻找的API在io模块中有文档记录 - ShadowRanger
3个回答

3

您的列表(my_list)只有1个项目 - 一个包含您想要的项目的列表。

如果您尝试打印print(len(my_list)),就会发现这一点,因此您的print(my_list[1])超出了范围,因为具有索引= 1的项目不存在。

当您创建一个空列表并附加输出时,您正在将一个项目添加到列表中,该项目是变量output保持值的内容。

要获得所需的内容,请执行以下操作

my_list = list(output)

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())]

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接