簡體   English   中英

如何迭代二維數組

[英]How to iterate 2D arrays

我被分配了關於 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)

二維數組作為列表的列表非常容易迭代。 關於如何迭代的簡單示例:

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/

只是為了添加到 Batcastle 的答案,以最簡單的方式顯示迭代:

您基本上是從列表中選擇一個列表,然后從該列表中選擇一個項目,因此如果您的數組是:

array = [['a','b','c'],['d','e','f'],['g','h','i']]

以下是您從中獲取值的方法:

# this would be equal to ['d','e','f']
x = array[1]

# this would be equal to 'h':
x = array[2][1]

# this would be equal to ['b','c']
x  = array[0][1:3]

請記住,在迭代時,它總是從第一個位置到但不包括最后一個位置。

希望有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM