gpt4 book ai didi

python - 嵌套(二维)字典的类迭代器?

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:36 26 4
gpt4 key购买 nike

我已经断断续续地使用 Python 几年了,但对于复杂的面向对象编程来说并不多,而且我很少使用字典作为结构。对于这个应用程序,我正在尝试在 map 上构建一个地理定位航路点数据库。

因此,我想创建一个能够访问二维字典结构并执行各种方法的容器类。为了可用性和可读性,我尝试实现各种容器方法,但我很难添加类功能。

我的容器类的片段

# Python standard libraries
from collections import defaultdict
from GeoWayPt import *
#===========================================================================
class GeoWayPtData():
""" Geodetic waypoint data container """

# Nested dictionary structure for equipment/waypoints
def equip_dict(self): return defaultdict(self.waypt_dict)
def waypt_dict(self): return GeoWayPt

def __init__(self):
""" Constructor """
#
self.AvailEquipIndex = 0

# Nested dictionary of equipment with waypoints
#
# First key for each equipment.
# Second key for each waypoint.
# [EquipNum][WayptNum]
self.dictWayPts = defaultdict(self.equip_dict)

我不确定如何实现 iter 和 next 方法以在下面的测试脚本中实现循环功能。

我的数据类的一部分

class GeoWayPt():
""" Geodetic waypoint container class """
def __init__(self):
""" Constructor """
# Equipment ID (integer, starting at 0)
self.ID = 0
# Equipment class (string description)
self.EquipClassStr = ''

我的测试脚本

from GeoWayPt import *
from GeoWayPtData import *

# 2-D data structure
data = GeoWayPtData()

waypt = GeoWayPt()
waypt.ID = 0
waypt.EquipClassStr = "foo"
# Add equipment 0
data.AddEquip(waypt)

waypt = GeoWayPt()
waypt.ID = 0
waypt.EquipClassStr = "bar"
# Add waypoint to equipment 0
data.AddWayPt(0, waypt)

waypt = GeoWayPt()
waypt.ID = 1
waypt.EquipClassStr = "can"
# Add equipment 1
data.AddEquip(waypt)

waypt = GeoWayPt()
waypt.ID = 1
waypt.EquipClassStr = "haz"
# Add waypoint to equipment 1
data.AddWayPt(1, waypt)

waypt = GeoWayPt()
waypt.ID = 1
waypt.EquipClassStr = "sum"
# Add another waypoint to equipment 1
data.AddWayPt(1, waypt)

# Functionality I'd like:
for equip in data:
for waypt in equip:
print waypt.ID, waypt.EquipClassStr

最佳答案

与其尝试在 GeoWayPtData 中支持迭代,不如在 GeoWayPtData 中迭代 defaultdict 更容易:

for equip in data.dictWayPts.itervalues():
for waypt in equip.itervalues():
print waypt.ID, waypt.EquipClassStr

当然,您也可以通过添加生成航路点的 __iter__ 将此功能添加到 GeoWayPtData:

    def __iter__(self):
for equip in self.dictWayPts.itervalues():
for waypt in equip.itervalues():
yield waypt

然后你可以这样做:

for waypt in data:
print waypt.ID, waypt.EquipClassStr

关于python - 嵌套(二维)字典的类迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8539673/

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