2016-10-29 6 views
1

以下のPythonスクリプトを実行しようとしたときにこのエラーが発生しました。文字列引数をfloat引数に転送し、たとえば、123.456を123.456に転送できるはずです。なぜこのエラーが出るのかわかりません。Python:TypeError:+: 'int'と 'NoneType'のサポートされていないオペランドタイプ

str2float = lambda x : float(x) 

あるいはfloat機能(なぜ最初の場所でstr2floatを定義の名前を変更することにより:

from functools import reduce 
def char2num(s1): 
    if s1 == '.': 
     pass 
    else: 
     return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s1] 

def str2float(s): 
    count = 0 

    ans = reduce(lambda x, y: 10*x + y,map(char2num,s)) 

    for x in range(len(s)): 
     if s[x] == '.': 
      count = x 
      break 
     else: 
      pass 
    for n in range(count): 
     ans /= 10 
    return ans 
print('str2float(\'123.456\') =', str2float('123.456')) 
+1

場合S1 =浮動小数点の不正確さを回避するために、位置の10パワーによって標準index機能と分割を用いたドットのインデックスを計算しますあなたは何も返しません... –

答えて

1

まず、私はあなたがそれを1行で行うことができることを知っていると仮定していますか? ):

str2float = float 

のは、今それを脇に置くと、あなたの問題に焦点を当ててみましょう:

Noneまたはそれ以外の文字をreduceに入力させることはできません。

ans = reduce(lambda x, y: 10*x + y,map(char2num,filter(lambda x:x!='.',s))) 

フルコード:

from functools import reduce 
def char2num(s1): 
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s1] 

def str2float(s): 
    count = 0 

    ans = reduce(lambda x, y: 10*x + y,map(char2num,filter(lambda x:x!='.',s))) 

    for x in range(len(s)): 
     if s[x] == '.': 
      count = x 
      break 
     else: 
      pass 
    for n in range(count): 
     ans /= 10 
    return ans 
print('str2float(\'123.456\') =', str2float('123.456')) 

結果:

str2float('123.456') = 123.45599999999999 

(精度の損失により、複数の除算に10をすることによって、あなたはこのように、たとえば、前にドットをフィルタリングする必要があります)

EDIT:あなたのドット/ディビジョンの処理は準最適です。別のアプローチを提案しましょう。 floatにドットが含まれていない場合は機能します。

from functools import reduce 
def char2num(s1): 
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s1] 

def str2float(s): 
    count = 0 

    ans = reduce(lambda x, y: 10*x + y,map(char2num,filter(lambda x:x!='.',s))) 

    if "." in s: 
     dotpos = s.index(".") 
    ans /= 10**dotpos 

    return ans 
print('str2float(\'123.456\') =', str2float('123.456')) 

結果:「」

str2float('123.456') = 123.456 
+0

ありがとうたくさんの! – Gemini

関連する問題