2013-08-01 12 views
-3

這是我迄今所做的:如何打破一個STR成一個列表

def file_to_dict(f): 

""" (file open for reading) -> dict of {float: int} 

f contains exchange rate changes as floating point numbers separated 
by whitespace. Return a dict with exchange rate changes as keys and the 
number of occurrences of the exchange rate changes as values. 
""" 

file = open(f, 'r') 
data = list(file.read().strip().split('\n')) 

的數據是:

0.0045 0.0160 -0.0028 -0.0157 -0.0443 -0.0232 -0.0065 -0.0080 0.0052 
-0.0052 -0.0283 -0.0087 -0.0020 -0.0080 -0.0065 -0.0290 0.0180 0.0030 
-0.0170 0.0000 -0.0185 -0.0055 0.0148 -0.0053 0.0265 -0.0290 0.0010 
-0.0015 0.0137 -0.0137 -0.0023 0.0008 0.0055 -0.0025 -0.0125 0.0040 

如何使每個號碼的項目在清單? 例如:[0.0045, 0.0160, etc...] or ['0.0045', '0.0160', etc...]

+0

看到我的答案在字典上的其他幫助 – Stephan

+0

爲了清晰起見,可以改進這個問題的標題 – Greg

回答

1

是這樣的?

>>> with open('fileName', 'r') as f: 
     newList = [] 
     for line in f: 
      newList.extend(map(float, line.split())) 


>>> newList 
[0.0045, 0.016, -0.0028, -0.0157, -0.0443, -0.0232, -0.0065, -0.008, 0.0052, -0.0052, -0.0283, -0.0087, -0.002, -0.008, -0.0065, -0.029, 0.018, 0.003, -0.017, 0.0, -0.0185, -0.0055, 0.0148, -0.0053, 0.0265, -0.029, 0.001, -0.0015, 0.0137, -0.0137, -0.0023, 0.0008, 0.0055, -0.0025, -0.0125, 0.004] 

因爲,你不能使用map(),這樣做

>>> with open('fileName', 'r') as f: 
     newList = [] 
     for line in f: 
      for elem in line.strip().split(): 
       newList.append(float(elem)) 
+0

I ca不使用地圖功能(我們還沒有學習它,因此應該使用其他方法)。我直觀地想要做的是去數據=列表(file.read()。strip()。split('\ n',''))或data = list(file.read()。strip()。split() '\ n'和'')),但它似乎不是分割函數的性質 – user2639519

+0

@ user2639519:請參閱編輯。 –

+0

謝謝,你的方法奏效。我也發現做data = list(file.read()。strip().split()也是一樣,每個數字都以列表形式出現 – user2639519

0

既然你不能使用地圖和大概沒有發電機或者,只需使用2迴路

而且它聽起來像你被允許使用字符串來存儲你的浮點數,這將有助於你的精度,因爲浮點數比較混亂。

stringlist = [] 
with open('fileName', 'r') as file: 
for line in file: 
    for item in line.split(): 
     stringlist.append(item)  # this stores strings 

擾流板,如果你想指望這些花車的出現,並把它們存儲在一個字典,因爲它似乎是你的任務,你可以這樣做:

myDict = {} 
for value in stringlist: 
    if value in myDict.keys(): # this would pose float comparison issues if you used float keys 
     myDict[value] += 1 
    else: 
     myDict[value] = 1 

print myDict 
0

列表理解:

list_ = [ 
    float(number) for line in open("filename", "r") 
    for number in line.strip().split() 
]