2017-07-21 10 views
0

ElementAbundanceという名前のフィールドを持つ特定のhdf5ファイルを読み込むスクリプトを作成しようとしています。このファイルには化学元素の分数値があります。ループの場合、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 

です:Exception: Element type [['Hydrogen']] not found in element abundance list.

Hydrogenelementsのリストに入れる必要があるので、どちらが奇妙ですか。また、発生した例外は、[['Hydrogen']]ではなく['Hydrogen']を返す必要があります。

私が追加できる追加情報があれば教えてください。

答えて

1

あなたのように関数を呼び出している場合:あなたは要素のリストを反復処理するとき、あなたは「、

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

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

次に「水素は、」単一項目のリストになっています文字列を反復して['Hydrogen']とマッチさせるのはリストなので、一致するものは見つかりません。

関連する問題