我正在创建一个程序,输出一个5x5的0矩阵。然后,我要求用户输入介于0到25之间的数字,这会将选定的元素变成1
我需要矩阵输出显示0,但是实际上,在幕后它需要像这样: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
例如:用户输入7.矩阵将输出:
/输出/ 请输入0-25之间的数字:
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
最简单的方法是什么?
当前代码:
def main():
grid = [[0 for row in range(5)]for col in range(5)] #creates a 5x5 matrix
#prints the matrix
for row in grid: #for each row in the grid
for column in row: #for each column in the row
print(column,end=" ") #print a space at the end of the element
print()
player1 = input("Please enter a number between 0-25: ")
main()
答案 0 :(得分:0)
您要查找的函数是numpy.unravel_index
,它将平坦索引(在5x5情况下为0-24)转换为整形索引。
另外,请注意,一个5x5矩阵将包含25个元素,范围是0-24,而不是0-25。
下面是一段代码,演示如何执行此操作。另外,我还添加了对用户输入的检查,因此输入的数字只能是平面索引范围内的整数。
import numpy as np
sh = (5,5)
a = np.zeros(sh)
print(a)
while True:
try:
player1 = int(input('Number1: '))
if player1 < 0 or player1 > a.size-1:
raise ValueError # this will send it to the print message and back to the input option
break
except ValueError:
print("Invalid integer. The number must be in the range of 0-{}.".format(a.size))
a[np.unravel_index(player1,sh)] = 1
print(a)
这是输出:
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
Number1: 7
[[0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
编辑(如果您确实需要列表)
要在列表上使用numpy
,只需将列表转换为numpy.array
,使用numpy.unravel_index
并将其转换回列表:
import numpy as np
sh = (5,5)
a_array = np.zeros(sh)
a_list = a_array.tolist() # Here numpy converts a to a list (your starting point)
a_array = np.array(a_list) # Here it converts it to a numpy.array
while True:
try:
player1 = int(input('Number1: '))
if player1 < 0 or player1 > a_array.size-1:
raise ValueError # this will send it to the print message and back to the input option
break
except ValueError:
print("Invalid integer. The number must be in the range of 0-{}.".format(a.size))
a_array[np.unravel_index(player1,sh)] = 1
a_list = a_array.tolist()
print(a_list)
您将以列表形式获得相同的输出
[[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]]