这是问题的要点。如果您愿意,可以阅读代码。
我将以下命令附加两个numpy数组列表:
np.append(list1,list2)
我所期待的是输出列表长度为len(list1)+ len(list2) 但相反,输出完全不同。 代码已关闭..它有点长......对此有所了解。 这种追加行动是否存在“陷阱”? 感谢
我无法弄清楚我做错了什么?让我只是编写代码和输出..以及我期待的和我得到的东西:( 还读取输出..我已突出显示错误的位置
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 :(得分:2)
答案 1 :(得分:1)
您的代码非常难以理解。
在我看来,你有两个列表 - list1
和list2
- 并且你想填充较短的列表以使它们具有相同的长度。要巧妙地做到这一点:
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 [])