For循环来自HDF5文件的单个字符串值

时间:2017-07-21 15:36:10

标签: python for-loop hdf5

我正在尝试编写一个脚本,该脚本读取具有名为ElementAbundance的字段的特定hdf5文件,该字段具有化学元素的分数值。

这就是我正在做的事情,我打开hdf5文件,我列出了该文件中的字段。如果文件包含ElementAbundance,则会检查field中我要求的元素是否在elements数组中。如果它在数组中,那么我想要将我要求的元素作为单个字符串返回。

我已经在其他地方查了过,ElementAbundance中的字段是

elements = ['Carbon', 'Helium', 'Hydrogen', 'Iron', 'Magnesium', 'Neon', 'Nitrogen', 'Oxygen', 'Silicon']

import h5py
from particleType import partTypeNum # This is another file that is unimportant in regards to my question

# Only necessary if gas (0) particle type

def loadElement(basePath,snapNum,partType,field=None):
    result = {}

    # This uses the above module to associate keys words with the letter 0    
    ptNum = partTypeNum(partType)
    gName = "PartType" + str(ptNum)

    # making sure fields is not a single element
    if isinstance(field, basestring):
        field = [field]

    # begin by opening the h5py file
    with h5py.File(snapPath(basePath,snapNum),'r') as f:

        # header = dict( f['Header'].attrs.items() )
        # nPart = getNumPart(header)

        # This creates a list for all the fields in the HDF5 file
        field_list = []
        for i in f[gName].keys():
            field_list.append(str(i))

        # This will check if the file has a "ElementAbundance" header
        for i in enumerate(field_list):
            # if the string is not inside the list, we raise an exception
            if "ElementAbundance" not in field_list:
                raise Exception("Particle type ["+str(ptNum)+"] does not have a field of elements")
            # If it is, we extract the chemical elements from inside the element abundance field.
            else:
                g = f[gName]['ElementAbundance'] # file contains elements
                elements = []
                for j in g.keys():
                    elements.append(str(j))


        # now for looping the lists values with their index
        for i,element in enumerate(elements):
            # if the element field is inside the elements list, we retrieve that element as a string
            if field == element:
                the_element = str(elements[i])
                return the_element
            # if their is a ElementAbundance field but the asked for field element is not in that list, raise and exception.
            else:
                raise Exception("Element type ["+str(field)+"] not found in element abundance list.")

        f.close()
    # testing to see if the above for loop returns a single string
    return the_element 

现在我测试一下,如果它返回字符串' Hydrogen',但是我返回了例外:Exception: Element type [['Hydrogen']] not found in element abundance list.

这很奇怪,因为Hydrogen应该在我所做的elements列表中。此外,引发的异常应该返回['Hydrogen']而不是[['Hydrogen']]

如果他们是我可以添加的任何其他信息,请告诉我们!

1 个答案:

答案 0 :(得分:1)

如果您将该功能称为:

loadElement(basePath,snapNum,partType,field='Hydrogen')

然后将'Hydrogen'变成单项目列表:

if isinstance(field, basestring):
        field = [field]

当您迭代元素列表时,您正在迭代字符串并将它们与['Hydrogen']匹配,这是一个列表,因此找不到匹配项。