[英]Swap two indices in Python 2D array
I wrote a function as follows:我写了一个函数如下:
def change_value(array):
for i in range(len(array)):
for j in range(len(array[i])):
if array[i][j]==0:
array[i][j],array[0][0]= array[0][0],array[i][j]
print(array[i][j],end=' ')
print()
array=[[1,2,3],[4,0,6],[7,8,5]]
change_value(array)
This function exchanges the values of the two desired indices after receiving the array.该函数在接收到数组后交换两个所需索引的值。 But the output was as follows:但输出如下:
1 2 3
4 1 6
7 8 5
What is the solution to this problem?这个问题的解决方案是什么?
The problem is you're printing each value as you go - with the zero value in position (1, 1) you have already printed out the 0th row that would have had a value swapped in a future iteration.问题是您正在打印每个值 - 在位置 (1, 1) 的零值您已经打印出第 0 行,该行将在未来的迭代中交换值。
Decouple the swapping code and the printing code:解耦交换代码和打印代码:
def change_value(array):
for i in range(len(array)):
for j in range(len(array[i])):
if array[i][j] == 0:
array[i][j], array[0][0] = array[0][0], array[i][j]
def print_array(array):
for row in array:
for cell in row:
print(cell, end=" ")
print()
array = [[1, 2, 3], [4, 0, 6], [7, 8, 5]]
print_array(array)
print("===")
change_value(array)
print_array(array)
While AKX solution is correct, note that the pythonic way to solve the problem would be虽然 AKX 解决方案是正确的,但请注意,解决问题的 Pythonic 方法是
import numpy as np
array = np.array([[1, 2, 3], [4, 0, 6], [7, 8, 5]])
mask = (array == 0)
array[mask], array[0, 0] = array[0, 0], array[mask]
print(array)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.