2011-06-02 79 views
0

我嘗試這樣做:從Python中的字符串解析元組的最佳方式是什麼?

def string_to_value(self, old_value, distribution_type, new_value_str): 
    parameter_names = distribution_type.parameters # a list of string 
    try: 
     parameter_values = ast.literal_eval(new_value_str) # a tuple or basic type hopefully 
    except SyntaxError: 
     raise ValueError('Syntax error during parse') 
    retval = copy.copy(old_value) 
    try: 
     if len(parameter_names) == 1: 
      setattr(retval, parameter_names[0], parameter_values) 
     else: 
      if len(parameter_names) != len(parameter_values): 
       raise BoostPythonArgumentError 
      for parm_name, parm_value in zip(parameter_names, 
              parameter_values): 
       setattr(retval, parm_name, parm_value) 
    except BoostPythonArgumentError: 
     raise ValueError('Lots of helpful text here') 
    return retval 

這適用於很多的情況下。 Boost.Python會在設定的時間自動檢查parm_value的類型。不幸的是,它不適用於包含'inf'的字符串。 ast.literal_eval當我希望它返回一個浮點數時提高ValueError('malformed string')。我不明白Python如何解析'inf',但literal_eval不能。

回答

0

您需要評估嗎?例如

a = "(1,2,3,4)" 
b = tuple(a.strip('()').split(',')) 
assert ('1','2','3','4') == b 
0

如果所有元素都具有相同的數字類型,那麼這個工程:

numpy.fromstring('1.3, 2.2, 5, inf, 2', sep=',') 

回報

array([ 1.3, 2.2, 5. , inf, 2. ]) 
相關問題