[英]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.