python - 如何迭代二维数组
问题描述
我被分配了一项关于 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/
推荐阅读
- php - 基于 Symfony 组件的依赖注入【抽象控制器】
- r - 将多面图与常见面结合起来
- python - 从 json 文件中选择随机值
- c# - 尝试显示错误消息时应用程序崩溃
- html - 具有两列的容器流体。右侧需要限制
- sql-server - 如何使用 onprem 中的 sqlpackage 提取 bacpac 并将其直接发送到 azure 存储帐户?
- python - numpy 大小在大列表上失败
- javascript - 如果我在尝试禁用/启用输入字段时添加 Thymeleaf th:field,JavaScript 不起作用
- java - 如何纠正eclipse tomcat服务器错误
- java - lombok 1.18.2 抛出 transformClassesWithDexBuilderForDebug