2012-10-16 3 views
-2

왜 내 목록 이해가 작동하지 않습니까? 매트릭스에서 난수를 스케일하려고합니다. 이것은 람다 함수로 작동하지만 목록 이해로는 작동하지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?내 목록 이해가 작동하지 않습니다.

import numpy as np 
import pylab as pl 
def RandomSource(N,x0,x1,y0,y1,c0,c1): 
    randSources = np.random.random((N,3)) 
    # print to double-check agruments of the function 
    print 'This are scaling values %s %s %s %s %s %s %s' % (N,x0,x1,y0,y1,c0,c1) 
    # below should scale a whole matrix 
    [x0 + x*(x1-x0) for x in randSources[:,0]] 
    [y0 + y*(y1-y0) for y in randSources[:,1]] 
    [c0 + c*(c1-c0) for c in randSources[:,2]] 
    return randSources 

xS = 10 
yS = -100 
cS = 5 
N = 1000 
newPoints = RandomSource(N,xS-5,xS+5,yS-3,yS+2,cS-1,cS+2) 

print type(newPoints) 
print 'newPoints x = %s' % newPoints[0,0] 
print '\nnewPoints = %s\nnewX = %s \nnewY = %s' % (newPoints[0:10], newPoints[0:10,0],     newPoints[0:10,1]) 

pl.scatter(newPoints[:,0], newPoints[:,1], s=20, c=newPoints[:,2], marker = 'x') 
pl.show() 

출력 :

newPoints = [[ 0.34890398 0.65918009 0.8198278 ] 
      [ 0.47497993 0.98015398 0.23980164] 
      [ 0.86359112 0.10184741 0.24804018]] 

하지만이 같은 예상 :

newPoints = [[ 6.4124458 -99.77854982 5.60905745] 
      [ 9.04459454 -99.63120435 4.08184828] 
      [ 14.94181747 -98.50800397 4.95530916]] 
+3

출력을 얻었습니까? 너는 무엇을 기대 했는가? –

+0

오류가 없으며 크기가 조정되지 않고 크기가 조정 된 행렬을 기대합니다. – tomasz74

+1

@ tomasz74 실제 질문을하고, 자신의 코드가 마음에 들지 않는다고 막연하게 질문해야합니다. – Marcin

답변

4

목록을 변경하지 않습니다 지능형리스트; 완전히 새로운 목록을 만듭니다. 그 할당 (randSources[:,1] = ...)를 작동하는지 잘 모르겠어요,하지만 일반적인 생각입니다 :

def RandomSource(N,x0,x1,y0,y1,c0,c1): 
    randSources = np.random.random((N,3)) 
    # print to double-check agruments of the function 
    print 'This are scaling values %s %s %s %s %s %s %s' % (N,x0,x1,y0,y1,c0,c1) 
    # below should scale a whole matrix 
    #[x0 + x*(x1-x0) for x in randSources[:,0]] 
    randSources[:,0] = map(lambda x: x0 + x*(x1-x0), randSources[:,0]) 

    randSources[:,1] = [y0 + y*(y1-y0) for y in randSources[:,1]] 
    randSources[:,2] = [c0 + c*(c1-c0) for c in randSources[:,2]] 
    return randSources 

참고 :이 결과를 저장하기 위해 이해의 결과를 할당해야합니다. 더 간단한 예 :

>>> l = [1, 2, 3, 4, 5] 
>>> [i*2 for i in l] 
[2, 4, 6, 8, 10] 
>>> l 
[1, 2, 3, 4, 5] 
>>> l = [i*2 for i in l] 
>>> l 
[2, 4, 6, 8, 10] 
관련 문제