python从文件中加载列表_从文本文件加载列表中找不到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])

问题是从文本文件中加载数字,然后将每个数字存储为变量,以便我可以得到它们的平均值.

我似乎无法找到一种方法来专门定位每个数字,只是每个字节不是我想要的.

解决方法:

你有两个主要问题.

首先,.append()用于将单个项添加到列表中,而不是用于将一个列表添加到另一个列表.因为您使用了.append(),所以您最终得到了一个包含一个项目的列表,该项目本身就是一个列表…不是您想要的,以及您的错误消息的说明.对于将一个列表连接到另一个列表.extend()或=会起作用,但是你应该问问自己在你的情况下是否有必要.

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

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

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

将条件添加到列表解析中的能力也是一种真正的复杂性保护.例如,如果您想跳过任何悄悄进入文件的空白/空白行:

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

标签:python,text-files,list

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值