python中input数组,python中用户输入的多维数组

I used Jupyter notebook, I am new to Python, I try to fetch value from user in multidimensional array how I do that? I write a little code, after put first value I get error that I don't understand

Error:

Traceback (most recent call last)

in

5 for i in range(lengthrow):

6 for j in range(lengthcol):

----> 7 arr[i][j]=int(input("enter value"))

8 print(arr)

IndexError: index 0 is out of bounds for axis 0 with size 0

code:

from numpy import*

arr = array([[],[]])

lengthrow=int(input("enter array row length"))

lengthcol=int(input("enter array col length"))

for i in range(lengthrow):

for j in range(lengthcol):

arr[i][j]=int(input("enter value"))

print(arr)

解决方案

I took @Austin great answer and made some little changes:

import numpy as np

n_rows = int(input("Enter number of rows: "))

n_cols = int(input("Enter number of columns: "))

arr = [[int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1))) for c in range(n_cols)] for r in range(n_rows)]

print(np.array(arr))

The output is:

Enter number of rows: 2

Enter number of columns: 3

Enter value for 1. row and 1. column: 1

Enter value for 1. row and 2. column: 2

Enter value for 1. row and 3. column: 3

Enter value for 2. row and 1. column: 4

Enter value for 2. row and 2. column: 5

Enter value for 2. row and 3. column: 6

[[1 2 3]

[4 5 6]]

You got an exception, because you initialized an empty array and used invalid indices. With this answer you generate the array after you have entered the users input.

Here is the long version of the one-liner (arr = [[...) which gives you the same result:

outer_arr = []

for r in range(n_rows):

inner_arr = []

for c in range(n_cols):

num = int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1)))

inner_arr.append(num)

outer_arr.append(inner_arr)

print(np.array(outer_arr))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值