首页 > 解决方案 > 如何访问和打印存储在字典中的类对象?

问题描述

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

标签: pythonpython-3.x

解决方案


我相信您的代码有一些缺陷: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']

推荐阅读