[英]Creating a list from user input using a for loop
I am trying to make loop in python where the user input an array 5 times and store them for each i from 1 to 5 in a[i],but my code didn't work.Here is my code : 我正在尝试在python中制作循环,用户在其中输入了5次数组,并将每个i从1到5存储在a [i]中,但是我的代码不起作用。这是我的代码:
import numpy
from numpy import linalg
import numpy as np
for i in range(5):
u[i]=np.array(input(" "))
print u[i]
First, you need to tell Python that u
is going to be a list. 首先,你需要告诉Python的是
u
将是一个列表。 Otherwise u[i]
will throw a NameError
because you're trying to access u
without having defined it. 否则
u[i]
会抛出NameError
因为您试图访问u
而未定义它。
Then, you need to grow the list dynamically, otherwise u[i]
will throw an IndexError
because, again, you're trying to reference u[i]
before it has been created. 然后,您需要动态地增加列表,否则
u[i]
会抛出IndexError
因为同样,您试图在创建u[i]
之前对其进行引用。
import numpy as np
u = []
for i in range(5):
u.append(np.array(input(" ")))
print u[i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.