2013-10-13 122 views
0

我已經從逗號分隔的文本文件中讀取數據(原始格式爲alpha_char,空間爲1,2,3,4,5,6,7,空間爲alpha_characters,爲新行字符)並輸出[['1,2,3,4,5,6,7'],['7,5,3,9,8,2,4'], etc](即一個字符串的列表),並希望將它們轉換爲[[1,2,3,4,5,6,7],[7,5,3,9,8,2,4], etc](即int列表)。因此,我會欣賞如何從文本文件中讀取數據到int列表列表或如何將我擁有的字符串列表轉換爲int列表列表。我知道,我在這裏很愚蠢。將字符串列表的列表轉換爲列表的列表int

+1

,如果它真的是一個逗號分隔的文件,你可以跳過手工的東西,'進口csv'和使用那? – KobeJohn

回答

0

使用列表理解:

>>> with open('file.txt') as f: 
...  rows = [line.strip().split(',') for line in f] 
... 
>>> rows 
[['1', '2', '3', '4', '5', '6', '7'], ['7', '5', '3', '9', '8', '2', '4']] 
>>> nums = [list(map(int, row)) for row in rows] 
>>> nums 
[[1, 2, 3, 4, 5, 6, 7], [7, 5, 3, 9, 8, 2, 4]] 

您還可以使用csv module

>>> import csv 
>>> 
>>> with open('file.txt') as f: 
...  reader = csv.reader(f) 
...  rows = [row for row in reader] 
... 
>>> rows 
[['1', '2', '3', '4', '5', '6', '7'], ['7', '5', '3', '9', '8', '2', '4']] 
+0

謝謝。我試圖按照你的描述做很多事情,但是在錯誤的地方。我現在得到int base10的無效文字,所以我需要看看我已經做了什麼。優秀的答案 – user1478335

0

要篩選號碼和轉換您的輸出,你可以做到以下幾點:

new_list = [ [ int(x) for x in convert_list.split(",") if x.isdigit() ] for sublist in oldlist for convert_list in sublist ] 

如果你想知道你是否有輸入這是不是一個數字,你可以省略.isdigit()和使用嘗試以下情況除外:

try: 
    [ [ int(x) for x in convert_list.split(",") ] for sublist in oldlist for convert_list in sublist ] 
except ValueError: 
    print("bad input") 
相關問題