遍历numpy数组列表

2 投票
2 回答
7279 浏览
提问于 2025-04-18 13:32

我有一个包含多维数组的列表,需要访问这些数组并对它们进行操作。

这里是一些示例数据:

list_of_arrays = map(lambda x: x*np.random.rand(2,2), range(4))
list_of_arrays
[array([[ 0.,  0.],[ 0.,  0.]]), array([[ 0.39881669,  0.65894242],[ 0.10857551,   0.53317832]]), array([[ 1.39833735,  0.1097232 ],[ 1.89622798,  1.79167888]]), array([[ 1.98242087,  0.3287465 ],[ 1.2449321 ,  2.27102359]])]

我有几个问题:

1- 我该如何遍历 list_of_arrays,让每次循环都返回一个单独的数组呢?
比如,第一次循环返回 list_of_arrays[0],最后一次循环返回 list_of_arrays[-1]

2- 我该如何将每次循环的结果作为另一个函数的输入呢?

我对Python还比较陌生。我最初的想法是在一个for循环里定义这个函数,但我不太清楚该怎么实现:

for i in list_of_array:
    def do_something():

我在想有没有人能提供一个好的解决方案。

2 个回答

1

你可以通过for循环来访问每一个数组,然后可以执行你想做的任何操作。

示例

使用内置函数

import numpy as np
list_of_arrays = map(lambda x: x*np.random.rand(2,2), range(4))
for i in list_of_arrays:
    print sum(i)

使用用户自定义函数

import numpy as np
def foo(i):
    #Do something here 

list_of_arrays = map(lambda x: x*np.random.rand(2,2), range(4))
for i in list_of_arrays:
    foo(i)

绘制数据以进行分析

import numpy as np
import matplotlib.pyplot as plt
list_of_arrays = map(lambda x: x*np.random.rand(2,100), range(4))
fig = plt.figure(figsize=(10,12))
j=1
for i in list_of_arrays:
    plt.subplot(2,2,j)
    j=j+1
    plt.scatter(i[0],i[1])
    plt.draw()
plt.show()

这样会给你这个结果:

Row comparison in 2*100 matrix
3

你在别的地方定义这个函数,然后在循环里调用它。你不需要在循环里一次又一次地定义这个函数。

def do_something(np_array):
    # work on the array here

for i in list_of_array:
    do_something(i)

举个例子,假设我对每个 array 调用 sum 函数。

def total(np_array):
    return sum(np_array)

现在我可以在 for 循环里调用它。

for i in list_of_arrays:
    print total(i)

输出结果

[ 0.  0.]
[ 1.13075762  0.87658186]
[ 2.34610724  0.77485066]
[ 1.08704527  2.59122417]

撰写回答