2012-07-05 38 views
0

問題:如何將txt中的浮點數作爲字符串來回答問題?

.TXT: 
194220.00 38.4397984 S 061.1720742 W 0.035 
194315.00 38.4398243 S 061.1721378 W 0.036 

的Python:

myList = ('38.4397984,061.1720742','38.4398243,061.1721378') 

回答問題。 How to take floats from a txt to a Python list as strings

代碼:

with open('haha.txt') as f: 
    for line in f: 
     words = line.split() 
     print words 
     my_list.append(words[1] + words[3]) 

我的測試代碼不會產生所期望的結果。它有什麼問題?我錯過了, ...

['38.4397984061.1720742', '38.4398243061.1721378'] 
+0

代碼是...? –

回答

0

你有沒有嘗試過的非常明顯:

my_list.append(words[1] + "," + words[3]) 

順便說一下,小小的評論:或許把這個問題作爲對你在另一個線程中已經接受的答案的評論而不是打開另一個問題會更合理。

+0

唉,他寫的東西在評論中不太合適。更別說無法正確格式化的代碼了...... – glglgl

0

我並不確切地知道你想要什麼,但我認爲

my_list.append((words[1], words[3])) 

增加了一個元組my_list,所以結果應該是

[('38.43979840', '061.1720742'), ('38.43982430', '061.1721378')] 

相反,你可以如做

my_list.append((float(words[1]), float(words[3]))) 

將表示數字的字符串轉換爲數字:

[(38.4397984, 61.1720742), (38.4398243, 61.1721378)] 
相關問題