首页 > 解决方案 > 如何迭代二维数组

问题描述

我被分配了一项关于 2D 数组的家庭作业,但我们没有时间复习它们。如果有人可以尝试引导我完成它,那将不胜感激或将我引导到一个有用的来源。我什至不知道从哪里开始,所以任何事情都有帮助。另外,如果您可以通过第一个可能会有所帮助。谢谢你。

import numpy as np


def modify_2d_array(array):
    """
    Given a 2d numpy array iterate through the values and set the value equal to the row*column number

    :param array: 2d numpy array
    """
    pass


def sum_threshold_2d_array(array, threshold):
    """
    Iterate through each element of the 2d array using nested loops.
    Sum up the values that are greater than a threshold value given as an input parameter.

    :param array: a 2d array
    :param threshold: a threshold value (valid int or float)
    :return: sum total of values above the threshold
    """
    pass


def clipping_2d_array(array, threshold):
    """
    Iterate through each element of the 2d array using nested loops.
    Set the values greater than a threshold value equal to the threshold value given as an input parameter.

    (E.g. if the threshold is 1 and there is a value 1.5, set the value to 1 in the array)

    :param array: a 2d array
    :param threshold: a threshold value (valid int or float)
    """
    pass


def create_identity_matrix(n):
    """
    Create a nxn sized identity matrix. The return type should be a list or numpy ndarray

    For more info: https://en.wikipedia.org/wiki/Identity_matrix

    For this exercise you can use nested loops to construct your 2d array or find an applicable function in the numpy library.

    :param n:
    :return: nxn ndarray where the diagonal elements are 1 and nondiagonal elements are 0
    """

    pass


if __name__ == "__main__":
    my_example_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    print(sum_threshold_2d_array(my_example_array, 5))
    print(clipping_2d_array(my_example_array, 5))
    print(create_identity_matrix(5))

    # Modifies existing array
    modify_2d_array(my_example_array)
    print(my_example_array)

标签: python

解决方案


作为列表的列表,二维数组的迭代相当简单。一个关于如何迭代的简单示例:

my_list = [[1,2,3],[4,5,6],[7,8,9]]
for each in my_list:
    # each is going to be equal to each list in my_list, so we can iterate over it with another, nested, for loop
    for each1 in each:
        # do what you want to do to each value
        # in this example, I'm just printing
        print(each1)

与此类似的东西应该允许您遍历大多数 2D 列表。

有关更多信息,我建议检查一下:https ://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/


推荐阅读