0

需要从一个数组中获取值,将它们放入一个函数并将它们放入另一个数组中。这意味着使用一对嵌套的 for 循环来完成。请帮忙。完整的初学者在这里。

编辑:好的澄清一下,我有一个包含各种值的二维数组。我想对所有这些值应用一个函数,并在它们通过函数后返回一个带有值的二维数组。我在 python 中工作。感谢您的快速回复和您可以提供的任何帮助!

EDIT3:示例代码:

import numpy as N

def makeGrid(dim):
    ''' Function to return a grid of distances from the centre of an array.
    This version uses loops to fill the array and is thus slow.'''
    tabx = N.arange(dim) - float(dim/2.0) + 0.5
    taby = N.arange(dim) - float(dim/2.0) + 0.5
    grid = N.zeros((dim,dim), dtype='float')
    for y in range(dim):
        for x in range(dim):
            grid[y,x] = N.sqrt(tabx[x]**2 + taby[y]**2)
    return grid

import math

def BigGrid(dim):
    l= float(raw_input('Enter a value for lambda: '))
    p= float(raw_input('Enter a value for phi: '))
    a = makeGrid 
    b= N.zeros ((10,10),dtype=float) #Create an arry to take the returned values
    for i in range(10):
        for j in range (10):
            b[i,j] = a[i][j]*2


if __name__ == "__main__":
    ''' Module test code '''
    size = 10 #Dimension of the array
    newGrid = BigGrid(size)
    newGrid = N.round(newGrid, decimals=2)
    print newGrid
4

7 回答 7

1

首先,您的代码中有以下行中的错误:

a = makeGrid

您正在设置a为一个函数,而不是一个数组。您应该具备以下条件:

a = makeGrid(dim)

这就是为什么TypeError当您尝试@abought 的答案时,您会遇到这种情况。

现在,要在 numpy 中逐元素应用操作,有很多可能性。如果要对数组中的每个元素执行相同的操作,最简单的方法是使用数组操作:

b = a * 2

(请注意,您不需要b事先声明。而且您也不需要任何循环。) Numpy 还有许多 C 优化函数,它们对数组的每个元素执行相同的操作。这些被称为ufuncs。您可以组合 ufunc 来获得按元素评估的复杂表达式。例如:

b = N.sin(a**2) + N.log(N.abs(a))

您的a数组 frommakeGrid()也可以使用数组操作和 numpy 更有效地创建mgrid

grid = N.mgrid[-dim//2 + 1:dim//2:0.5, -dim//2 + 1:dim//2:0.5]
grid = N.sqrt(grid[0]**2 + grid[1]**2)

如果您想对每个数组元素执行不同的操作,事情会变得更加复杂,并且可能无法避免循环。对于这些情况,numpy 有一种方法可以使用ndenumerateor分解 nD 数组上的循环ndidex。你的例子ndenumerate

for index, x in N.ndenumerate(a):
    b[index] = x * 2

这比多个循环要快,但应尽可能使用数组操作。

于 2012-12-10T23:42:39.570 回答
1

根据您的问题,您似乎正在使用 Numpy。如果您不太关心速度,您可以简单地使用 numpy 数组调用该函数;该函数将为您对整个数组进行操作。

无需显式编写迭代,但如果您能找到一种方法来利用 numpy 的特殊功能,那将比使用设计为一次操作一个元素的函数更快。但是,除非您使用的是非常大的数据集,否则这应该没问题:

import numpy as np
>>> g = np.array( [ [1,2,3], [ 4,5,6] ] )
array([[1, 2, 3],
       [4, 5, 6]])
>>> def myfunc( myarray ):
...     return 2 * myarray
... 
>>> myfunc(g)
array([[ 2,  4,  6],
       [ 8, 10, 12]])
于 2012-12-10T16:16:03.697 回答
1
def map_row(row):
    return map(some_function,row)

 map(map_row,my_2d_list)

大概是我会怎么做...

于 2012-12-10T15:45:22.460 回答
0

从我从问题的上下文中可以得到的信息以及2d-array通常的含义看起来您正在尝试执行以下操作:

>>>> array2d = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
>>> def add_two( v ):
...     return v + 2
... 
>>> [ [ add_two( v ) for v in row ] for row in array2d ]
[[2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6]]

list上面使用了一个列表理解,它与使用两个嵌套的 for 循环相同,在这种情况下更具可读性,并且当您描述的list是什么而不是构建它时,涉及的方法的直接交互更少。

于 2012-12-10T15:34:40.773 回答
0

使用嵌套循环很容易做到这一点:

def my_function(n): # n will become y from the next part
   new_num = # do whatever you want with it
   return new_num

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # just an example
new_list, final_list = [], [] # multiple assignment
for x in my_list:
   print x
   new_list = []
   for y in x:
      # y is now the first value of the first value of my_list--- 1.
      my_num = my_function(y)
      new_list.append(my_num)
   final_list.append(new_list)
print final_list

那应该这样做。

回报:[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

于 2012-12-10T15:58:26.540 回答
0

这是一个带双地图的单行

map(lambda x:map(func, x), l)

例子:

l=[[1,2,3],[4,3,1]]
map(lambda x:map(lambda x:x*10,x),l)

[[10, 20, 30], [40, 30, 10]]
于 2012-12-10T15:42:22.413 回答
-2
for(int i; i < x; i++)
   for(int j; j < y; j++)
       array2[i][j] = func(array2[i][j])

类似的东西?

于 2012-12-10T15:04:26.913 回答