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])
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]
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)
添加回答
举报