gpt4 book ai didi

python - 如何访问和打印存储在字典中的类的对象?

转载 作者:行者123 更新时间:2023-12-01 09:02:22 26 4
gpt4 key购买 nike

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

最佳答案

我相信您的代码有一些缺陷:当您像这样拆分时,road_list 将有一个空字符串作为最后一个元素。我认为使用内置函数 lines = file.readlines() 比使用 road_list = [line.strip().split() for line inlines 更好]

要访问字典中的元素,您可以通过键获取它们,然后通过索引或常规 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']

关于python - 如何访问和打印存储在字典中的类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52372755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com