gpt4 book ai didi

python - 使用 PyROOT 访问 TTree 中的嵌套容器

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

在 PyROOT 中,很容易从树中读取值,即打印叶子 val :

file = TFile('file.root')
tree = file.Get('tree')
for entry in tree:
print entry.val

也很容易从 STL 中读取值 vector<float> , vec :

for entry in tree: 
print entry.vec[1]

但是嵌套向量呢,即 nested类型 vector<vector<float> > ?运行

for entry in tree: 
print entry.nested[0][0]

会抛出一个 TypeError: 'vector<vector<float> >' object is unindexable .

处理此问题的最佳方法是什么? (如果不需要在 ROOT 字典中加载则更好)

最佳答案

这对我在 python 中使用索引很有用。

    >>>from ROOT import *
>>>vec1 = std.vector('double')()
>>>vec2 = std.vector('double')()
>>>vec_vec = std.vector(std.vector('double'))()

>>>for i in range(3):
>>> vec1.push_back(i)
>>>for i in range(5):
>>> vec2.push_back(i)
>>>vec_vec.push_back(vec1)
>>>vec_vec.push_back(vec2)

>>>len(vec_vec)
2
>>>len(vec_vec[0])
3
>>>len(vec_vec[1])
5
>>>vec_vec[1][2]
2.0

在你的例子中错误说:

    TypeError: 'vector<vector<float> >' object is unindexable

在调用构造函数 std.vector(type)() 之后,您有不同的类型表明内存空间分配器正在工作。

    >>>type(vec1)
<class 'ROOT.vector<double,allocator<double> >'>
>>>type(vec_vec)
<class 'ROOT.vector<vector<double,allocator<double> >,allocator<vector<double,allocator<double> > > >'>

要从 TTree 导入此类向量,请使用 setBranchAddress,如本例所示:

    >>>tree = file.Get('tree')
>>>tree.SetBranchAddress("nested",vec_vec)
>>>N = tree.GetEntries()
>>>for i in range(N):
>>> vec_vec.clear()
>>> tree.GetEntry(i)
>>> print vec_vec[0][0]

另请注意,使用后这可能会明显加快

   >>>tree.setBranchStatus('*',0)
>>>tree.setBranchStatus('nested',1)

关于python - 使用 PyROOT 访问 TTree 中的嵌套容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057076/

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