2012-03-25 86 views
-2

這裏是問題的要點。如果你想,那麼你可以閱讀代碼。列表附加奇怪的錯誤:python

我追加2名numpy的陣列列表以one..by以下命令:

np.append(list1,list2) 

我所期待的是,輸出列表爲len(list1的)+ LEN(列表2) 的長度但相反,輸出的長度完全不同。 該代碼是關閉..它的位很長..對此。 這種類型的附加操作有沒有「陷阱」? 謝謝

我無法弄清楚我做錯了什麼?讓我只寫代碼和出來..我期待什麼,我得到:( 也讀取輸出。我已經強調了錯誤所在

So I input two list and their corresponding labels. 
import numpy as np 
def list_appending(list_1, list_2, y_one, y_two): 
count_1 = len(list_1) 
count_2 = len(list_2) 
    #if one list is bigger than other.. then add synthetic values shorter list 
    #and its target y variable 
if count_1 > count_2: 

    diff = count_1 - count_2 
    new_y = np.zeros(diff) 
    new_feature_list = generate_synthetic_data(list_2,diff) 

    print "appended ", len(new_feature_list)," synthetic entries to first class (label0)" 
elif count_2 > count_1: 
    diff = count_2 - count_1 
    new_feature_list = generate_synthetic_data(list_1,diff) 
    new_y = np.ones(diff) 
    print "appended ", len(new_feature_list)," synthetic entries to second class (label1)" 
else: 
    diff = 0 
    new_feature_list = [] 
    print "nothing appended" 
print "class 1 y x",len(y_one), len(list_1) 
print "class 2 y x",len(y_two), len(list_2) 

print "len l1 l2 ",len(list_1) , len(list_2) 
f_list = np.append(list_1,list_2) # error is in this line.. unexpected.. see output 
print "first x append ", len(f_list) 
f_list = np.append(f_list,new_feature_list) 
print "second x append ", len(f_list) 
print "new features ", len(new_y), len(new_feature_list) 
new_y_list = np.append(y_one,y_two) 
print "first y append ", len(new_y_list) 
new_y_list = np.append(new_y_list,new_y) 
print "second y append ", len(new_y_list) 
# print features_list_1.shape, features_list_2.shape, new_feature_list.shapes 
#print len(features_list_1[0]), len(features_list_2[0]), len(new_feature_list[0]) 


print "appended ", len(f_list), len(new_y_list) 
return f_list, new_y_list 

輸出:

appended 35839 synthetic entries to first class (label0) 
class 1 y x 42862 42862 
class 2 y x 7023 7023 
len l1 l2 42862 7023 
first x append 349195 <----- This is the error line 42862 + 7023 = 49885 
second x append 600068 
new features 35839 35839 
first y append 49885 <------------This append was just fine.. 
second y append 85724 
appended 600068 85724 
+0

任何人都可以解釋爲什麼-1? – Fraz 2012-03-25 21:53:03

+0

什麼是np?我只是瞎了? – tchap 2012-03-25 21:54:09

+0

oh np作爲np導入numpy – Fraz 2012-03-25 21:54:35

回答

2

doc page

If axis is None, out is a flattened array. 

我的猜測是,你不想壓平列表。

1

你的代碼是非常非常難以理解

正如我所看到的,您有兩個清單 - list1list2 - 並且您想填充較短的清單以使其長度相同。要做到這一點整齊:

n, m = len(list1), len(list2) 

if n > m: 
    # Make the shorter list come first 
    list1, list2 = list2, list1 
    n, m = m, n 

list1.append(generate_padding(m-n) if n < m else [])