python - 如何访问和打印存储在字典中的类对象?
问题描述
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 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']
推荐阅读
- r - 提供特定值时从数据框中删除因子
- python - seaborn 热图未正确显示
- reactjs - 在 aws LAMBDA 中使用 axios 的参数
- python-3.x - 使用python脚本中的pandas库处理超过1000行的csv文件以合并csv文件时出错
- stackdriver - 我可以将有效负载添加到对 Opsgenie 的 Stackdriver 调用吗
- c# - asp.net core - AddService 使用选项 iniside IServiceCollection 扩展
- azure-devops - Azure Dev Ops 内部部署
- sdk - 如果需要国家和邮政编码权限,可以对 Alexa 提出请求吗?
- mapbox - Mapbox决定重叠顺序
- apache-kafka - WSO2 无法从 Kafka 主题接收数据