亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 Number.txt 文件轉換為列表

如何將 Number.txt 文件轉換為列表

胡說叔叔 2021-12-29 10:56:58
我想修復我曾經做過的代碼中的邏輯和語法錯誤,但我重置了代碼,認為它是錯誤的,從那以后一直無法弄清楚。我在代碼中添加了 line = line.split,還將 numbers.append 更改為 numbers.sort,并將 int(我理解為什么 int 不起作用,但我不確定用什么替換它)來輸入。主文件number_file=open("Numbers.txt")count=0numbers = []sum = 0for line in "Numbers.txt"數字.txt050100
查看完整描述

2 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

我不是 100% 確定您要做什么,但這是基于我對您的問題的理解的答案:


# Create a list named numbers

numbers = []


# Open the input file in read only

with open ('Numbers.txt', 'r') as input:

  # read each line of the input file

  for line in input:

    # append each line to the list numbers

    # rstrip removes the \n from the strings

    numbers.append(line.rstrip())



print (type(numbers))

# outputs

<class 'list'>


print (numbers)

# outputs

['0', '50', '100']


# converts your list elements to int for summing 

results = list(map(int, numbers))

print (sum(results))

# outputs

150

如果這不正確,請告訴我,我會調整我的答案。


查看完整回答
反對 回復 2021-12-29
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

打開文件的一個好方法是使用上下文:


with open('path/to/file/Numbers.txt','r') as input_file:

    for line in input_file.readlines():

        do_stuff # knowing that they are string so you should convert to int


查看完整回答
反對 回復 2021-12-29
  • 2 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號