Python一行循环输入

2024-04-25 04:09:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何根据用户的选择获取输入。一、 “你想输入多少个数字?”如果答案是5,那么我的数组在一行中有5个空格,5个整数用空格隔开。在

num = []
x = int(input())
for i in range(1, x+1):
    num.append(input())

上面的代码可以工作,但是输入被enter分割(下一行)。一、 电子邮箱:

^{pr2}$

我想得到:

2
145 1278

我很感激你的帮助。在

编辑:

x = int(input())
while True:
    attempt = input()
    try:
        num = [int(val) for val in attempt.split(" ")]
        if len(num)== x:
            break
        else:
            print('Error')
    except:
        print('Error')

这似乎有效。但是为什么我得到“内存限制超出”错误?在

编辑: 不管我用哪种方法,我都会遇到同样的问题。在

x = int(input())
y = input()
numbers_list = y.split(" ")[:x]
array = list(map(int, numbers_list))
print(max(array)-min(array)-x+1)

或者

x = int(input())
while True:
    attempt = input()
    try:
        num = [int(val) for val in attempt.split(" ")]
        if len(num)== x:
            break
        else:
            print('Error')
    except:
        print('Error')

array = list(map(int, num))
print(max(array)-min(array)-x+1)

或者

z = int(input())
array = list(map(int, input().split()))
print(max(array)-min(array)-z+1)

Tags: inmapforinputerrorvalminarray
3条回答

最简单的方法是:

input_list = []

x = int(input("How many numbers do you want to store? "))

for inputs in range(x):
    input_number = inputs + 1
    input_list.append(int(input(f"Please enter number {input_number}: ")))

print(f"Your numbers are {input_list}")

您希望输入只在一行上有什么原因吗?因为你只能限制存储(或打印)多少个数字,而不是用户输入的数量。用户可以继续输入。在

假设您想在一行中输入数字,下面是一个可能的解决方案。用户必须像您在示例中那样拆分数字。如果输入格式错误(例如“21 asd 1234”)或数字与给定长度不匹配,则用户必须再次输入值,直到输入有效为止。在

x = int(input("How many numbers you want to enter?"))
while True:
    attempt = input("Input the numbers seperated with one space")
    try:
        num = [int(val) for val in attempt.split(" ")]
        if len(num)==x:
            print(num)
            break
        else:
            print("You have to enter exactly %s numbers! Try again"%x)
    except:
        print("The given input does not match the format! Try again")

您无需x即可使用此选项:

num = [int(x) for x in input().split()]

相关问题 更多 >