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

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

將文本文件讀取為 dict

將文本文件讀取為 dict

森欄 2021-12-09 11:00:05
我的文本文件看起來像這樣..每行由一個空格分隔。dream 4.345 0.456 6.3456play 0.1223 -0.345 5.3543faster 1.324 2.435 -2.2345我想寫字典并將其打印如下...dream: [4.345 0.456 6.3456]play: [0.1223 -0.345 5.3543]faster: [1.324 2.435 -2.2345]我的代碼如下。請糾正我這個...with open("text.txt", "r") as file:     for lines in file:        line = lines.split()        keys = b[0]         values = b[1:]        d[keys] = valuesprint d
查看完整描述

3 回答

?
青春有我

TA貢獻1784條經驗 獲得超8個贊

對于 python3,如果你想得到想要的結果:


d = {}


with open("text.txt", "r") as file:

    for lines in file:

    line = lines.split()

    keys = line[0] 

    values = list(map(float, line[1:]))

    d[keys] = values

for k in d :

    print(k , d[k])


查看完整回答
反對 回復 2021-12-09
?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

你可以這樣試試。


輸入.txt


dream 4.345 0.456 6.3456

play 0.1223 -0.345 5.3543

faster 1.324 2.435 -2.2345

編寫器.py


output_text = '' # Text

d = {} # Dictionary


with open("input.txt") as f:

    lines = f.readlines()


    for line in lines:

        line = line.strip()

        arr = line.split()

        name = arr[0]

        arr = arr[1:]


        d[name] = arr

        output_text += name + ": [" + ' '.join(arr) + "]\n"


output_text = output_text.strip() # To remove extra new line appended at the end of last line


print(d)

# {'play': ['0.1223', '-0.345', '5.3543'], 'dream': ['4.345', '0.456', '6.3456'], 'faster': ['1.324', '2.435', '-2.2345']}


print(output_text)

# dream: [4.345 0.456 6.3456]

# play: [0.1223 -0.345 5.3543]

# faster: [1.324 2.435 -2.2345]


with open("output.txt", "w") as f:

    f.write(output_text)

輸出.txt


dream: [4.345 0.456 6.3456]

play: [0.1223 -0.345 5.3543]

faster: [1.324 2.435 -2.2345]


查看完整回答
反對 回復 2021-12-09
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

這很簡單。請參閱下面的代碼。


  dictionary = {}

  with open("text.txt", "r") as file:  

      for lines in file:

          line = lines.split()

          dictionary[line[0]] = line[1:]

  print(dictionary)


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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