简体   繁体   English

python中的用户输入矩阵(n * n + 1)

[英]User Input matrix(n*n+1) in python

this code is out put a[i][j] start with a[0,0] but i want it start with a[1,1] How have i do??这段代码输出 a[i][j] 以 a[0,0] 开头,但我希望它以 a[1,1] 开头,我该怎么办?

import numpy as np
n = int(input("How many variable you find "))
a = np.zeros((n,n+1))
print('Enter Augmented Matrix:')
for i in range(n):
    for j in range(n+1):
        a[i][j] = float(input( f'a[{i},{j}]= '))
print(a)

Using range(n) starts at 0 included, and n exlcuded, in math this is [0;n[ , to start at 1 do range(1, n) giving you使用range(n)0开始包括在内,并排除n ,在数学中这是[0;n[ ,从1开始做range(1, n)给你

for i in range(1, n):
    for j in range(1, n + 1):

If you input 4 at first question, then fill with ones you'll get :如果你在第一个问题中输入4 ,然后填写你会得到的:

[[0. 0. 0. 0. 0.]
 [0. 1. 1. 1. 1.]
 [0. 1. 1. 1. 1.]
 [0. 1. 1. 1. 1.]]

If you use the following it goes to far, because arrays are indexed 0-base , so if you say an array is length 5, the box indexes are 0,1,2,3,4如果您使用以下内容,它会走得很远,因为数组的索引为0-base ,因此如果您说数组的长度为 5,则框索引为0,1,2,3,4

for i in range(1, n + 1):
    for j in range(1, n + 2):

SOLUTION解决方案

If you want to fill all values, but just change the thing you print for the user, do如果您想填充所有值,但只是更改为用户打印的内容,请执行

for i in range(n):
    for j in range(n + 1):
        a[i][j] = float(input(f'a[{i + 1},{j + 1}]= ')) # +1 there

change this:改变这个:

   for i in range(n):
        for j in range(n+1):
            a[i][j] = float(input( f'a[{i},{j}]= '))

to this:对此:

for i in range(1,n):
    for j in range(1,n+1):
        a[i][j] = float(input( f'a[{i},{j}]= '))

Similarly you can try同样你可以试试

 for i in range(n-1):
     for j in range(n):
         a[i+1][j+1] = float(input( f'a[{i},{j}]= '))

May I ask why do you want to start with a[1][1]?请问为什么要以a[1][1]开头?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM