如何将 Number.txt 文件转换为列表

我想修复我曾经做过的代码中的逻辑和语法错误,但我重置了代码,认为它是错误的,从那以后一直无法弄清楚。


我在代码中添加了 line = line.split,还将 numbers.append 更改为 numbers.sort,并将 int(我理解为什么 int 不起作用,但我不确定用什么替换它)来输入。


主文件


number_file=open("Numbers.txt")

count=0

numbers = []

sum = 0


for line in "Numbers.txt"

数字.txt


0

50

100


胡说叔叔
浏览 160回答 2
2回答

慕妹3146593

我不是 100% 确定您要做什么,但这是基于我对您的问题的理解的答案:# Create a list named numbersnumbers = []# Open the input file in read onlywith open ('Numbers.txt', 'r') as input:&nbsp; # read each line of the input file&nbsp; for line in input:&nbsp; &nbsp; # append each line to the list numbers&nbsp; &nbsp; # rstrip removes the \n from the strings&nbsp; &nbsp; numbers.append(line.rstrip())print (type(numbers))# outputs<class 'list'>print (numbers)# outputs['0', '50', '100']# converts your list elements to int for summing&nbsp;results = list(map(int, numbers))print (sum(results))# outputs150如果这不正确,请告诉我,我会调整我的答案。

繁星淼淼

打开文件的一个好方法是使用上下文:with open('path/to/file/Numbers.txt','r') as input_file:&nbsp; &nbsp; for line in input_file.readlines():&nbsp; &nbsp; &nbsp; &nbsp; do_stuff # knowing that they are string so you should convert to int
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python