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

2024-09-30 02:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

问题是从文本文件中加载数字,然后将每个数字存储为一个变量,这样我就可以得到它们的平均值。 我似乎找不到一种方法来具体定位每个数字,只是每个字节不是我想要的。你知道吗


Tags: thetoinputmy数字openlistfile
3条回答

你会有两个主要问题。你知道吗

首先,.append()用于将单个添加到列表中,而不是将一个列表添加到另一个列表中。因为您使用了.append(),所以您得到了一个包含一个项目的列表,而该项目本身就是一个列表。。。不是你想要的,还有错误信息的解释。将一个列表连接到另一个.extend()+=是可行的,但您应该问问自己,在您的情况下这是否是必要的。你知道吗

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

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

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

在列表理解中添加条件的能力也是一个真正的复杂性节约。例如,如果要跳过文件中的任何空白行:

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

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

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

你的列表(我的列表)只有一个项目-一个包含你想要的项目的列表。你知道吗

如果您尝试print(len(my\u list)),则可以看到这一点,因此您的print(my\u list[1])超出范围,因为index=1的项不存在。你知道吗

当您创建一个空列表并附加输出时,您正在向列表中添加一个项,这就是变量输出为值保留的内容。你知道吗

想得到你想要的就做吧

my_list = list(output)

相关问题 更多 >

    热门问题