2015-10-20 56 views
1

我初始化了一个空的numpy数组,我想用一些计算值填充它。我的代码如下:用不同的计算值填充numpy数组

Distance=np.empty(6,dtype=np.uint8) 
for i in range(0,6): 
    x=hamming_distance(tst,LUT[i]) 
    print 'x={}' .format(x) 
    print 'type_x={}' .format(type(x)) 
    #Distance.fill(x) 
    np.append(Distance,x) 
    print 'Distance={}' .format(Distance) 

输出我得到的是

x=1 
type_x=<type 'numpy.uint8'> 
Distance=[3 3 3 3 3 3] 
---------- 
x=3 
type_x=<type 'numpy.uint8'> 
Distance=[3 3 3 3 3 3] 
---------- 
x=1 
type_x=<type 'numpy.uint8'> 
Distance=[3 3 3 3 3 3] 
---------- 
x=1 
type_x=<type 'numpy.uint8'> 
Distance=[3 3 3 3 3 3] 
---------- 
x=1 
type_x=<type 'numpy.uint8'> 
Distance=[3 3 3 3 3 3] 
---------- 
x=3 
type_x=<type 'numpy.uint8'> 
Distance=[3 3 3 3 3 3] 
---------- 

和我期待Distance[1 3 1 1 1 3]。我使用了np.fill,但这不起作用,因为它每次都会用x填充阵列,输出将是[3 3 3 3 3 3]

注意: tstLUT[i]是uint8 numpy阵列。

任何人都可以帮助我吗? 感谢

+0

什么是错的:'距离[i] = x'? 'np.append'返回附加的副本,所以基本上你没有在你的循环中做任何事情(除了计算'x',然后丢弃它)。 – zeroth

+0

非常感谢您的工作。 – motaha

回答

0

我宁愿执行列表理解: [hamming_distance(tst,LUT[x]) for x in range(0, 6)]
np.array([hamming_distance(tst,LUT[x]) for x in range(0, 6)]).astype('uint8')