2014-05-03 30 views
0

我有一些代碼:堆疊/連接數組和和「無」?

# first round 
curr_g = np.array([]) 
temp_g = np.array([1,2,3]) 

if curr_g is not None: 
    curr_g = temp_g 
    print "in is not none" 
else: 
    curr_g = np.c_[curr_g, temp_g] 
    print "in is none" 

print "curr_g: " 
print curr_g 

#second round 
temp_g = np.array([4,5,6]) 
if curr_g is not None: 
    print "in is not none" 
    curr_g = temp_g 
else: 
    print "in none" 
    curr_g = np.c_[curr_g, temp_g] 

print "curr_g: " 
print curr_g 

和上面的輸出如下:

in is not none 
curr_g: 
[1 2 3] 
in is not none 
curr_g: 
[4 5 6] 

爲什麼在地球上的條件進入「不關」兩次都在嗎? curr_g在被分配temp_g之後在第二輪中僅爲「非無」。

我的目標是,在第一輪,因爲curr_g確實是空的,應當與temp_g填充,而第二次,它實際上應該得到級聯到temp_g,成爲如下:

[ 
1 4 
2 5 
3 6 
] 

我怎樣才能做到這一點?

回答

1

如果你想檢查None,你應該明確指定None

curr_g = None 

正如BrenBarn提到的,您分配一個空numpy陣列,這是沒有更多的等於None不是空蟒蛇名單。

2

「空」與None不一樣。 None是一個特定的對象,它與你的(或任何)numpy數組不同,所以你的數組不是None

如果你想檢查你的數組是否爲空,只要做if curr_g。也就是說,如果你所要做的只是用其他東西來覆蓋它,那麼爲curr_g創建一個空數組並沒有多大意義。你可以用curr_g = None初始化它,然後你的is None檢查就可以工作。