該函數旨在將文件讀入字典中,使用birdnames a keys和權值作爲值。它正在做我想要的,但它不是通過所有的線路,我不知道爲什麼!幫助一個女孩出去? 這裏是我的代碼:將文件讀入字典python
def bird_weights(filename):
bird_dict = {}
f = open(filename, "r")
for line in f:
new_line = line.split(":")
bird_type = new_line[0].capitalize()
bird_weight = new_line[1].strip().split(' ')
bw_list = [float(i) for i in bird_weight]
bird_dict[bird_type] = bw_list
if bird_type in bird_dict:
bird_dict[bird_type].extend(bw_list)
else:
bird_dict[bird_type] = bw_list
return bird_dict
.txt文件是:
bluebird:78.3 89.3 77.0
TANAGER: 111.9 107.65
BlueBird: 69.9
bluebirD: 91.9
tanager: 108.0 110.0
和代碼是爲了產生
{"Bluebird":[78.3, 89.3, 77.0, 69.9, 91.9],"Tanager": [111.9, 107.65, 108.0, 110.0]}
什麼,我得到的是:
{"Bluebird":[91.9, 91.9], "Tanager": [108.0, 110.0, 108.0, 110.0] }
我不確定爲什麼
@eumiro雅我修正了我的想法。它被更新。 –