2014-03-26 55 views
1

其中,我的項目需要從文件中檢索距離信息,將數據轉換爲整數,然後將它們添加到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-任何及所有的幫助是極大的讚賞。

謝謝你的時間。

+0

您好像在'ValueError'輸出中沒有'1513'後面加了另一個引號。 – kojiro

+0

相關:[Python 3.3代碼示例,查找文件中所有整數的總和](http://stackoverflow.com/a/20024735/4279) – jfs

+0

謝謝你的方法,這給了我一個好主意,以便如何接近我的矩陣。在將距離加載到它之後,它應該能夠給出任何兩個給定城市的距離。看起來不錯。 – Yarou

回答

3

您從文件中獲得的所有信息都是一個字符串。您必須解析信息並將其轉換爲程序中的不同類型和格式。

  • int(distances)不會因爲工作,因爲你已經注意到,距離是一個字符串列表。您不能將整個列表轉換爲整數。 (什麼纔是正確的答案?)
  • int(distances[0])工作原理是因爲您只將第一個字符串轉換爲整數,而字符串表示整數,因此轉換工作。
  • int(distances[1])不起作用,因爲由於某種原因,列表的第二個和第三個元素之間沒有逗號,所以它隱式連接到字符串1513 2410。這不能轉換爲整數,因爲它有一個空格。

有可能爲你工作了幾個不同的解決方案,但這裏有幾個明顯的人對你的使用情況:

distance.extend([int(elem) for elem in line.split()]) 

,如果你有一定的每一個元素這隻會工作line.split()返回的列表可以進行此轉換。你也可以做全distance名單後一次全部:

distance = [int(d) for d in distance] 

distance = map(int, distance) 

你應該嘗試一些解決方案並實施,你覺得給你正常工作的最佳組合之一,可讀性。

+0

「線路」顧名思義是一條線;你不應該對它調用'.splitlines()'。如果每行有一個整數,那麼'int(line)'應該工作。通過示例列表判斷,該行中可能有多個整數。如果它們是空格分隔的,那麼'distance.extend(map(int,line.split()))' – jfs

+0

謝謝 - 無意識地複製並粘貼了它,但沒有修復。 –

+0

這是一個非常有啓發性的迴應,謝謝。我還沒有讓他們工作,我會嘗試J.F.的建議,看看是否能解決這個問題。 – Yarou

1

我的猜測是你想分割所有的空白,而不是換行符。如果文件不是很大,只是讀這一切:

distances = map(int, open('file').read().split()) 

如果某些值是不是數字:

distances = (int(word) for word in open('file').read().split() if word.isdigit()) 

如果文件非常大,使用一臺發電機,以避免閱讀它全部一次:

import itertools 
with open('file') as dists: 
    distances = itertools.chain.from_iterable((int(word) for word in line.split()) for line in dists)