class node():
def __init__(self,city,distance,speed,highway):
self.city = city
self.distance = distance
self.speed = speed
self.highway = highway
file=open("testDocument.txt","r")
f1=file.read()
newdict=dict()
road_list = [lines.split() for lines in f1.split("\n")]
for line in road_list:
firstcity=node(line[1],line[2],line[3],line[4])
secondcity=node(line[0],line[2],line[3],line[4])
newdict[line[0]] = (newdict.get(line[0], []) + [firstcity])
newdict[line[1]] = (newdict.get(line[1], []) + [secondcity])
现在字典中存储的值是对象,如何访问特定的对象,例如城市或距离?
文本文件具有以下格式的数据:
City1 City2 24 45 ME_16
City1 City3 4 45 ME_6/15/16
City1 City4 73 45 ME_6/15
City2 City5 2 45 WI_29
答案 0 :(得分:1)
我相信您的代码有一些缺陷:road_list
像这样拆分时,最后一个元素将包含一个空字符串。我认为使用内置功能lines = file.readlines()
比使用road_list = [line.strip().split() for line in lines]
更好。
要访问字典中的元素,您可以通过键获取它们,然后通过索引或常规python for循环访问所需的节点:
class node():
def __init__(self, city, distance, speed, highway):
self.city = city
self.distance = distance
self.speed = speed
self.highway = highway
file = open("testDocument.txt", "r")
lines = file.readlines()
road_list = [line.strip().split() for line in lines]
newdict = dict()
for line in road_list:
firstcity = node(line[1], line[2], line[3], line[4])
secondcity = node(line[0], line[2], line[3], line[4])
newdict[line[0]] = (newdict.get(line[0], []) + [firstcity])
newdict[line[1]] = (newdict.get(line[1], []) + [secondcity])
def list_property(key, prop):
result = []
for node in newdict[key]:
if prop == 'city':
result += [node.city]
if prop == 'distance':
result += [node.distance]
if prop == 'speed':
result += [node.speed]
if prop == 'highway':
result += [node.highway]
return result
print(list_property('City1', 'city'))
print(list_property('City1', 'speed'))
示例文件的输出:
['City2', 'City3', 'City4']
['45', '45', '45']