【发布时间】:2021-08-10 11:12:17
【问题描述】:
有人可以解释一下为什么将这个txt.file传输到字典的代码是我在下面写的答案,因为我不明白流程。
任务:将此txt文件转换为字典
house_price.txt=
land, building, distance_to_center, price
70, 50, 15, 500
70, 60, 30, 400
70, 60, 55, 300
100, 50, 30, 700
100, 70, 25, 1000
100, 70, 50, 650
120, 100, 20, 2000
120, 80, 50, 1200
150, 100, 50, 1800
150, 90, 15, 3000
答案:
file_house_price = open("house_price.txt", "r")
data_house_price = file_house_price.readlines()
file_house_price.close()
key_house_price = data_house_price[0].replace("\n","").split(",")
house_price = []
for lines in data_house_price[1:]:
lines_house_price = lines.replace("\n","").split(",")
dict_house_price = dict()
for i in range(len(lines_house_price)):
dict_house_price[key_house_price[i]] = lines_house_price[i]
house_price.append(dict_house_price)
print(house_price)
我想问一下这个key_house_price = data_house_price[0].replace("\n","").split(",")的replace和split是什么意思 以及为什么索引为 0,以及此行背后的含义是什么 -> 对于 data_house_price[1:] 中的行和 这一行 -> dict_house_price[key_house_price[i]] = lines_house_price[i]
【问题讨论】:
-
您能不能更具体地说明您不明白的地方?另请注意
csv模块可以为您执行此操作。 -
谢谢回复,我想问一下这个key_house_price = data_house_price[0].replace("\n","").split(",")中replace和split是什么意思以及为什么索引为0,以及这行背后的含义是什么->对于data_house_price[1:]中的行和这一行-> dict_house_price[key_house_price[i]] =lines_house_price[i],谢谢
-
@jonrsharpe 这看起来像是一项学校作业,因此使用图书馆的教育意义不大。
-
@anna 这是大约 4 个单独的问题,其中许多已包含在现有教程(例如 sopython.com/wiki/What_tutorial_should_I_read%3F)和文档(字符串方法:docs.python.org/3/library/stdtypes.html#str.replace)中。
标签: python dictionary txt