Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我的列表理解不起作用_Python - Fatal编程技术网

Python 我的列表理解不起作用

Python 我的列表理解不起作用,python,Python,为什么我的列表理解不起作用?我尝试在矩阵中缩放随机数。它作为lambda函数工作,但不作为列表。我做错了什么 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 sc

为什么我的列表理解不起作用?我尝试在矩阵中缩放随机数。它作为lambda函数工作,但不作为列表。我做错了什么

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]]

列表理解不会改变列表;它创建了一个全新的列表。您必须指定理解结果以存储结果:

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
注意:我不确定这个任务是否有效(
randSources[:,1]=…
),但这是总体思路。一个简单的例子:

>>> 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]

你得到了什么输出?你期待什么?我没有错误,只是没有缩放,我写得很清楚,我期待缩放matrix@tomasz74你必须问我们一个实际的问题,而不是含糊其辞地抱怨你不喜欢自己的代码。我没有说你需要给出一个错误,但是你得到了什么你没有预料到的输出?为什么错了?给。