简体   繁体   English

接受多个用python中的空格分隔的用户输入,并将它们附加到列表中

[英]accepting multiple user inputs separated by a space in python and append them to a list

How can I accept multiple user inputs separated by a space? 如何接受多个用户输入,并用空格分隔? I don't know the number of inputs, but I do know they are all ints. 我不知道输入的数量,但我知道它们都是整数。

Here's some example inputs: 以下是一些示例输入:

13213 412 8143
12 312
1321 142 9421 9 29 319 

I know can do this if I know the number of inputs beforehand, but I'm having trouble making this generic. 如果我事先知道输入的数量,我知道可以做到这一点,但是我很难使这个通用。 I could just ask the user to input how many groups of ints he will input: 我可以要求用户输入他将输入多少组整数:

inputs = int(raw_input("Enter number of raw inputs "))
num = []
for i in xrange(1, inputs):
    num.append(raw_input('Enter the %s number: '))

But I am looking for a more elegant solution that doesn't require asking the user 2 questions. 但是我正在寻找一种更优雅的解决方案,不需要向用户询问2个问题。

s = raw_input("Please enter your numbers: ")

mynums = [int(i) for i in s.split()]
# OR
mynums = map(int, s.split())

尝试这个:

nums = [int(i) for i in raw_input("Enter space separated inputs: ").split()]

for python 2.x 对于python 2.x

x,y = map(int,raw_input().split()) x,y = map(int,raw_input()。split())

it take two variable x and y of int type separated by space and you can replace int with your desired type 它需要两个int类型的变量x和y,它们之间用空格隔开,并且可以将int替换为所需的类型

for python 3.x 对于python 3.x

x,y = input().split() x,y = input()。split()

it takes two variables x and y of string type separated by space and you have to convert explicitly 它需要两个用空格分隔的字符串类型的变量x和y,并且必须显式转换

x,y=map(int,input().split()) #这将使输入以空格分隔并映射#into int

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

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