该函数旨在将文件读入字典中,使用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雅我修正了我的想法。它被更新。 –