2017-02-01 3 views
-1

謝罪私の元々の説明は明らかではなかったので、文字列を10進数に変更し、Python(3.6)の値を2 dpに設定するにはどうすればいいですか?

データファイルをスライスして、フィールドのリストとデータの固定幅ファイルから辞書を作成しました。私は数値とインサートに文字列を変換する必要がある流動比率(1234年)と酸試験(5678)のデータに

これをプリントアウトするとき、私は次の取得
data_format_keys = { 
      ("CURRENT-RATIO", 120, 127), 
      ("ACID-TEST", 127, 134), 
      ("NOTES", 134, 154 
      } 

...

Current Ratio = 1234 
Acid Test = 5678 
Notes = These are my notes 

計算に使用する小数点(これらのフィールドはメインフレームファイルからのものなので、正しいフォーマットに変換する必要があります)。

予想される出力がある...

Current Ratio = 12.34 #This is an integer/float 
Acid Test = 5.678 #This is an integer/float 
Notes = These are my notes #This is still a string 

私は元のリストから変換する必要があるフィールドのリストを作成しましたが、私は、変換

 for k,v in data_format_keys.items(): 
      if k in data_format_keys == headerdict[i[1]]: 
       line = line.replace(k, v) 
     fo.write(line) 

print(headerdict) 
をどのように適用するかで苦労しています

ここで、headerdictは作成される初期の辞書であり、data_format_keysは変換するフィールドのリストです。

どのような考えですか? おかげ

+0

1)無関係なコードがたくさんありますが、それは最小限の例ではありません。 2)あなたは... 100で割りますか? –

+0

'float(text)/ 100'ですか? – asongtoruin

+0

値が変換されると、100で除算されると思います。私は小数点を挿入しようとしていたが、これは理にかなっている。ありがとう。 – Leigh

答えて

0

はこれを試してみてください:pythonので良く

#createlist from current output 
thelist = [('Current Ratio', 1234), ('Acid Test', 5678), ('Notes', 'These are my notes') ] 
#create dict with just notes 
notes = dict([i for i in thelist if i[0] == "Notes"]) 
#create list without notes 
thelist = [i for i in thelist if i[0] != "Notes"] 
#create list of keys 
thelist1 = [i[0] for i in thelist] 
#create list of formatted numbers 
thelist2 = [float(i[1]/100) for i in thelist] 
#merge into dict 
thelist = dict(zip(thelist1, thelist2)) 
#create empty dict 
desired = {} 
#update dict with previously created dicts 
desired.update(thelist) 
desired.update(notes) 
print (desired) 

誰かが、より効率的なコードを書くことができるかもしれないが、これは良い出発点でなければなりません。

+0

これを辞書の特定の値にどのように適用するかわかりませんか? – Leigh

+0

'(" CURRENT-RATIO "、120、127)' あなたは見たいですか:** 1201.27 **または** 1.20、1。27 **? – Olufon

+0

{( "CURRENT-RATIO"、120、127)、( "ACID-TEST"、127,134)}固定ファイルを分割しているので、120は開始位置、127は現在の比率の終了です。これは、ファイルから価値を得て、辞書を作成しています。私が持っている問題は、この値とAcid-Testの値を計算のための数値に変換する必要がありますが、Notesをテキストとして残すことです。 – Leigh

0

必要に応じて書式付き出力を使用できます。ここで

は一例です。

#Inputs 
meal_cost = float(input("Enter meal price: ")) 
drink_cost = float(input("Enter drinks cost: ")) 

#Calculation 
total_cost = meal_cost + drink_cost 

#Output 
print("Your total bill is {:.2f} USD".format(total_cost)) 

あなたの出力は次のようになります。

Enter meal price: 7.49 
Enter drinks cost: 2.99 
Your total bill is 10.48 USD 

はこれが助けたなら、私に教えてください。 :)

+0

これを辞書の特定の値にどのように適用するかわかりませんか? – Leigh

関連する問題