简体   繁体   English

如何使用for循环从用户那里获取多个输入?

[英]How to take multiple inputs from user using for loop?

for i in range(n - 1):
        nums = int(input('Enter numbers: '))

INPUT:输入:

Enter numbers: 1
Enter numbers: 2
Enter numbers: 3
Enter numbers: 4

This is the output I am getting but I want the output to be in a single line, numbers that I am entering should be in a single line like 1 2 3 4. No commas no apostrophe这是我得到的 output 但我希望 output 在一行中,我输入的数字应该在一行中,如 1 2 3 4。没有逗号没有撇号

Please tell any solution请告诉任何解决方案

You can ask for a single input and then split it into words with the str.split() method您可以请求单个输入,然后使用str.split()方法将其拆分为单词

# Get the input
nums = input('Enter numbers :')

# Split and map to `int`
nums = nums.split()
nums = list(map(int, nums))

You can append it first into a list你可以 append 它先进入一个列表

def myfunction(n):
    return [input('Enter numbers: ' for _ in range(n - 1)]

numbers = myfunction(5)

Enter numbers: 1
Enter numbers: 2
Enter numbers: 3
Enter numbers: 4

And then, you can use " ".join(numbers)然后,您可以使用" ".join(numbers)

result = " ".join(numbers)
print(result)

1 2 3 4

If you do not even want to have the space:如果您甚至不想拥有空间:

result2 = "".join(numbers)
print(result2)

1234

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

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