2015-11-13 23 views
1

我是新來的Python,所以請不要在這個問題笑......Python:如何用逗號形成數組?

我有一個文件中的一些陣列,下面

100 23 35 44 47 511 
100 60 77 68 45 76 
100 97 99 89 91 14 
100 53 65 

顯示我已閱讀文件,並得到了每一行用下面的代碼,

f = file('new.txt') 
lines = f.readlines() 
f.close() 
results = [] 
for line in lines: 
    print line 

但爲了把它們作爲一個函數的輸入,如下,

clf.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) 

我想我需要格式化我的數組,使方括號([])中的每個數組,並在它們之間添加逗號。 最終的格式我需要的就是這樣的

clf.fit ([[100,23,35,44,47,511], [100,60,77,68,45,76], [100,97,99,89,91,14]], [100,53,65]) 

如何才能實現呢?

+0

在上面的例子中沒有使用'results'。 'clf1'從哪裏來? – Dan

+0

@丹對不起,我沒有寫出整個代碼片。 clf = linear_model.LinearRegression(),這是scikit-learn的一個函數 – KathyLee

回答

1

只是將每行分割成一個列表並創建一個列表(本質上是一個數組)列表。

final_array = [] 

with open('new.txt') as f: 
    for line in f: 
     temp_list = [int(x) for x in line.strip().split()] 
     if len(temp_list) > 0: # don't append an empty list (blank line) 
      final_array.append(temp_list) 

print final_array 

你可能想做一些額外的理智檢查,但是這完成了基本的想法。

+0

謝謝!這個代碼的最後一個數組是[[''100','23','35','44','47','\ n'],['100','60','77','68 '','77','100','97','99','89','91','\ n'],['100','100','43',' 64','64']]。我怎樣才能擺脫'\ n'? – KathyLee

+0

@KathyLee列表理解可以在同一行代碼中完成,請參閱更新 – Dan

+0

感謝您的編輯! :) – KathyLee

1

您可以使用numpy.loadtxt()將文件作爲數組加載。或者,如果您不想使用numpy,最好使用csv模塊加載數據並將它們轉換爲整數。

import csv 

with open('new.txt') as f: 
    spam_reader = csv.reader(f,delimiter=' ') 
    my_array = [map(int,row) for row in spam_reader] 

注意,如果你不知道你的數據的驗證前面的代碼將引發ValueError,這在這種情況下,你需要使用try-except表達式來處理異常。

my_array = [] 
for row in spam_reader: 
    try: 
     my_array.append(map(int,row)) 
    except ValueError: 
     # do stuff