如何在python中从用户读取数组元素

如何在python中从用户读取数组元素,python,arrays,Python,Arrays,我试图将数组元素读取为 4 #no. of elements to be read in array 1 2 3 4 我通过引用其他答案尝试了什么 def main(): n=int(input("how many number you want to enter:")) l=[] for i in range(n): l.append(int(input())) 如果我将输入作为 4 #no. of elements to be read 1 2

我试图将数组元素读取为

4 #no. of elements to be read in array
1 2 3 4 
我通过引用其他答案尝试了什么

def main():

    n=int(input("how many number you want to enter:"))
    l=[]
    for i in range(n):
        l.append(int(input()))
如果我将输入作为

4 #no. of elements to be read
1
2
3
4
但如果我试着给予

4 #no. of element to be read

1 2 3 4
我得到的错误是:

ValueError: invalid literal for int() with base 10: '1 2 3 4'

请帮我解决这个问题

因为Python中没有输入分隔符,所以您应该使用并拆分从用户收到的输入:

lst = your_input.split()

您的第一种方法还可以,对于第二种方法,请使用以下方法:

n=int(input("how many number you want to enter:"))
l=map(int, input().split())[:n] # l is now a list of at most n integers
这将在用户输入的拆分部分(即示例中的
1
2
3
4
)上启用该功能

它还使用切片(映射后的
[:n]
)进行切片,以防用户放入更多整数。

函数
input()
返回用户输入的字符串。
int()
函数希望将数字作为字符串转换为相应的数值。因此
int('3'))
将返回3。但是当您键入类似
1234
的字符串时,函数
int()
不知道如何转换它

n = input("how many number you want to enter :")

l=readerinput.split(" ")
您可以按照第一个示例进行操作:

    n = int(input('How many do you want to read?'))
    alist = [] 

    for i in range(n):
        x = int(input('-->'))
        alist.append(x)
以上要求您一次只能输入一个数字

另一种方法是分开绳子

    x = input('Enter a bunch of numbers separated by a space:')
    alist = [int(i) for i in x.split()]

split()
方法将数字列表作为字符串返回,不包括空格

我认为您的意思是,当您输入诸如“1 2 3 4”之类的字符串作为输入时,会引发错误。这是因为Python无法将包含非int字符的字符串转换为int。您需要拆分文本(
.split()
)将工作并使用结果数组。此外,这会使for循环冗余,但最好向用户指定数字应以空格分隔。