python - 如何访问元组的多维列表?
问题描述
我正在填充 NamedTuple 结构的多维 (2D) 列表,如下所示:
from typing import NamedTuple
class Halo(NamedTuple):
ID: int
axis: str
event_file: str
我声明一个空的 2D 列表:
halo_arr = [[[] for i in range(nhalo_bins)] for j in range(nperbin)]
然后,我在循环中使用上述各个结构填充列表:
my_item = Halo(int(IDarr_shuf[j][i]), axis_arr[j], evt_file)
halo_arr[nhalos[hbin]][hbin] = my_item
我可以用元组结构填充这个二维列表,并访问单个元素:
例如
print(halo_arr([0][5].ID))
但我希望能够访问整个 ID 数组(或元组的任何其他数组):
例如
print(halo_arr.ID)
这样我就可以将整个二维数组作为数据集放入 hdf5 文件中:
例如
fh5.create_dataset("/Halos/IDs",data=halo_arr.ID)
然而,我得到这个错误:
print(halo_arr.ID)
AttributeError:“列表”对象没有属性“ID”
我在这里不知所措,可能没有使用最佳结构。
解决方案
访问该列表列表中的单个属性将需要更明确地表达如何访问元组,具体取决于您需要作为输出的内容。例如使用列表推导:
[t.ID for row in halo_arr for t in row] # if you want it flat
[[t.ID for t in row] for row in halo_arr] # if you want it 2D
第一个(平面列表)相当于:
result = list()
for row in halo_arr: # Go through the first dimension (row is a list)
for t in row: # Go through tuples of the row
result.append(t.ID) # add ID to flat list
# result will be [id1, id2, id3, ...]
第二个(2D)相当于:
result = list()
for row in halo_arr: # Go through the first dimension (row is a list)
IDlist = list() # prepare a row of IDs
for t in row: # Go through tuples of the row
IDlist.append(t.ID) # add to row of IDs
result.append(IDlist) # add row of IDs to result
# result will be [ [id1, id2, id3, ...],
# [id8, id9, id10, ...]
# ... ]
推荐阅读
- if-statement - aarch64 有条件地加载/存储的方式是什么?
- python - 如何散点图2具有拥有颜色的数组列表?
- gradle - 在 Windows 机器上使用 gradle 构建/编译最新的 SalaJS(1.3+)?
- javascript - 在 React 中使用 JavaScript 过滤图像
- php - 我按什么顺序处理对我的 Web 表单的用户输入?
- colors - Directline bot-如何更改用户气泡的字体颜色
- javascript - JavaScript SVG不断地将动画元素附加到SVG元素
- java - 创建查询,如“A 是“b”,C 是“””(Spring Boot/Spring Data w/Mongo)
- bash - Maven 构建失败但退出代码仍为 0
- node.js - 除我的本地开发机器外,所有设备上的 Google OAuth 客户端授权错误