其中,我的項目需要從文件中檢索距離信息,將數據轉換爲整數,然後將它們添加到128 x 128矩陣中。將存儲爲字符串的數字列表轉換爲整數Python 2.7
我在從行讀取數據時處於僵局。
distances = []
with open(filename, 'r') as f:
for line in f:
if line[0].isdigit():
distances.extend(line.splitlines())`
這將產生一個字符串列表:
我找回它。
而
int(distances) #does not work
int(distances[0]) # produces the correct integer when called through console
然而,空間取得foobar以後的程序。 一個列表的例子:
['966']['966', '1513' 2410'] # the distance list increases with each additional city. The first item is actually the distance of the second city from the first. The second item is the distance of the third city from the first two.
int(distances[0]) #returns 966 in console. A happy integer for the matrix. However:
int(distances[1]) # returns:
Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '1513 2410'
我有更Python解決方案,如列表理解和類似輕微的偏愛,但在reality-任何及所有的幫助是極大的讚賞。
謝謝你的時間。
您好像在'ValueError'輸出中沒有'1513'後面加了另一個引號。 – kojiro
相關:[Python 3.3代碼示例,查找文件中所有整數的總和](http://stackoverflow.com/a/20024735/4279) – jfs
謝謝你的方法,這給了我一個好主意,以便如何接近我的矩陣。在將距離加載到它之後,它應該能夠給出任何兩個給定城市的距離。看起來不錯。 – Yarou