如何解决Python中的嵌套数据结构
我正在尝试创建一个将用于地理空间分解的数据结构 - 基本上采用顶部 10x10 网格并能够分解其中的每个网格。我正在为结构使用命名元组。为了复制较低层的结构,我在单元格中使用了“对象”类型,以便它可以包含较低层的网格。
代码如下,当我将nestedGrid 分配给对象类型时,我收到以下错误消息。我怎样才能达到我想要的结果?
回溯(最近一次调用最后一次):文件 “/Users/bryon/git_repo/SIT719/Task_9_1HD/main.py”,第 53 行,在 adaptivegrid.adaptivegrid(working_dataset,bounds,task_lat,task_long,"adaptive0.html") 文件 “/Users/bryon/git_repo/SIT719/Task_9_1HD/adaptivegrid.py”,第 47 行,在 自适应网格 c1.lowerGrid = nestedGrid AttributeError: 无法设置属性
from collections import namedtuple
import pandas as pd
import numpy as np
Point = namedtuple('Point','x y')
pt1 = Point(1.0,5.0)
pt2 = Point(2.5,1.5)
print(pt1,pt2)
Coord = namedtuple('Coord','lat long')
Bounds = namedtuple('Bounds','llCoord urCoord')
Cell = namedtuple('Cell','Bounds noisyCount lowerGrid')
# Calculate the grid and store in a data structure. Structure should have:
#
pt1 = Coord(1.0,2.0)
pt2 = Coord(5.0,6.0)
b = Bounds(pt1,pt2)
cell = Cell(b,7.2,object)
# Create a 10x10 grid of Cells and set [0][0] to some test data
grid = np.empty(shape=(10,10),dtype=object)
grid[0][0] = cell
# Now create a nested grid in in grid[0][0]
c1 = grid[0][0]
# Create a 2x2 grid to nest
nestedGrid = np.empty(shape=(2,2),dtype=object)
# Assign the nested grid to [0][0]
c1.lowerGrid = nestedGrid
# Create some test data for thenested grid and store in [1][1] of the nested grid
c2 = Cell(b,3.14,object)
nestedGrid[1][1] = c2
# Print the cell in the nested grid
print(grid[0][0].lowerGrid[1][1])
解决方法
命名元组和普通元组一样是不可变的。所以你不能改变一个值。但是有 _replace
方法可以通过创建新实例来替换值。
代替
# Assign the nested grid to [0][0]
c1.lowerGrid = nestedGrid
做
# Assign the nested grid to [0][0]
grid[0][0] = grid[0][0]._replace(lowerGrid=nestedGrid)
(您不能在此处将其分配给 c1
,因为这只会更改变量 c1
,而不是网格中的值)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。