迭代多个数组来执行任务?

2021-04-11 23:36:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有9个数组,每个数组包含19个值。在

假设它们是a1,a2,a3,a4,a5,a6,a7,a8,a9(每个a1,a2…a9每个包含19个值),我们称它们为a数组。

我还有9个数组,每个数组包含19个值。在

假设它们是b1,b2,b3,b4,b5,b6,b7,b8,b9(每个b1,b2…b9每个包含19个值),并将它们称为b数组。

我现在想取每个数组的第一个值和每个数组的第一个值,比如19个值的新数组。然后我用numpy.std计算这19个值的标准差。在

然后,我想再次迭代这些数组,但这次每个数组的第二个值以此类推,直到最后一个(第19个)值,并执行上述操作。在

如果我只有2个数组(比如a1b1),我可以使用zip这样的数组:

div_array = [] # The empty array that will have the divided values
for a,b in zip(a1,b1):
    div = a/b
    div_array.append(div)

std = np.std(div_array)

在我冗长的案件中,如何重复上述内容??

编辑:

最后,需要19个不同的标准差,即,我计算第一个值,然后计算第二个值,依此类推。。在

3条回答
网友
1楼 ·

所以不久前我写了一个类,它基本上满足了你的要求。唯一的诀窍是必须向类传递每个数组的迭代器列表。在

column_iter_traversal.py

"""
This code will take in a iterator of iterators. You can view the first
iterator as the rows of a graph (a matrix being a specific case of graphs)
and each iterable giving you the columns (or nodes) of that graph.

so if you have a graph
[[1, 2],
[3],
[4, 5]]

we'd expect the iterator to return [1, 3, 4, 2, 5]
"""

class ColumnTraversalIter():
    """
    This is a class which is used to contain the currently travered state.
    This is the class which defines the returned object for
    column_traversal_iter. The iter that function returns is an instance of
    this class.
    """
    def __init__(self, iter_of_iters):
        # Build a list of iterators
        self.iter_list = []
        for it in iter_of_iters:
            self.iter_list.append(it)
        self.current_iter_index = 0

    def __iter__(self):
        return self

    def __next__(self):
        # Get the next value from the current iterator
        try:
            return_val = next(self.iter_list[self.current_iter_index])
            self.current_iter_index = self._increment_index(
                self.current_iter_index,
                len(self.iter_list))
            return return_val
        except StopIteration:
            # When we run into a stop iteration we know that the current
            # iterator is out of values. Remove the current iterator from
            # the iterator list.
            del self.iter_list[self.current_iter_index]
            # If we are out of iterators it's time to raise StopIteration
            if len(self.iter_list) == 0:
                raise StopIteration
            else:
                # Otherwise, set the current_iter_index and recall next
                self.current_iter_index = self._increment_index(
                    self.current_iter_index,
                    len(self.iter_list))
                return self.__next__()
        except IndexError:
            # Someone called __next__ when there aren't any iterators left in
            # the iter_list.
            raise StopIteration

    @staticmethod
    def _increment_index(iter_index, wrap_length):
        if iter_index + 1 > wrap_length:
            print("returning 0")
            return 0
        else:
            print("returning {}".format(iter_index + 1))
            return iter_index + 1

def column_traversal_iter(iter_of_iters):
    """

    args:
        iterator: a iterator of iterators. If there aren't any iterators or
                  there are non iterator elements this will explode.
    returns a COlumnTraversalIter
    """
    return ColumnTraversalIter(iter_of_iters)

tests.py

^{pr2}$

你可以通过

divisor_iter_list = []
for a_list in a_lists:
    divisor_iter_list.append(iter(a_list))

dividend_iter_list = []
for b_list in b_lists:
    divident_iter_list.append(iter(b_list))


divisor_iter = ColumnTraversalIter(divisor_iter_list)
dividend_iter = ColumnTraversalIter(divident_iter_list)
for divisor, dividend in zip(divisor_iter, dividend_iter):
    # Do calculations.
网友
2楼 ·

如果你用numpy来除法,为什么不使用它来除法呢?在

>>> # You can create these array in a loop if you want
>>> a = np.array([a1, a2, a3, ..., a9])
>>> b = np.array([b1, b2, b3, ..., b9]) 
>>> c = np.std(a / b, 0)

示例(关于np.std的详细信息):

^{pr2}$
网友
3楼 ·

您可以在另一个数组中分别使用ab数组。是的

a[0] = a1a[1] = a2等等,b也是一样的

然后像:

for i in range(length(a)):
    div_array = []
    for j in range(length(a[i])):
        div = a[i][j]/b[i][j]
        div_array.append(div)

    std.append(np.std(div_array))

然后有一个数组std,其中包含您想要的所有值。在

当然,如果ab的长度相同,a[0]和{}等长度相同,那就可以了。你的情况也是如此。在

相关问题