Python 在从文本文件加载列表中找不到列表索引

Python list index not found in loading list from text file

作业是让用户输入 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])

问题是从文本文件中加载数字,然后将每个数字存储为一个变量,以便我可以获得它们的平均值。 我似乎无法找到一种方法来专门定位每个数字,只是每个字节都不是我想要的。

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

如果你尝试 print(len(my_list)) 你可以看到这个,所以你的 print(my_list[1]) 超出了范围,因为索引 = 1 的项目没有存在。

当您创建一个空列表并追加输出时,您是在向列表中添加一项,这是变量输出所持有的值。

想要得到你想要的就去做

my_list = list(output)

您可以稍微更改程序的结尾,它会起作用:

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

您将遇到两个主要问题。

首先,.append() 用于将单个 item 添加到列表,而不是将一个列表添加到另一个列表。因为你使用了 .append() 你最终得到了一个包含一个项目的列表,而那个项目本身就是一个列表......不是你想要的,以及你的错误信息的解释。将一个列表连接到另一个列表 .extend()+= 会起作用,但您应该问问自己,在您的情况下是否有必要这样做。

其次,您的列表元素是字符串,您希望将它们作为数字使用。 float() 将为您转换它们。

一般来说,你应该研究一下"list comprehensions"的概念。他们使这样的操作非常方便。以下示例创建一个新列表,其成员分别是 .readlines() 输出的 float()ed 版本:

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

将条件添加到列表理解中的能力也是真正的复杂性节省器。例如,如果您想跳过文件中的任何 blank/whitespace 行:

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