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,而不是网格中的值)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...