接受python中用空格隔开的多个用户输入,并将它们附加到列表中 [英] accepting multiple user inputs separated by a space in python and append them to a list

查看:631
本文介绍了接受python中用空格隔开的多个用户输入,并将它们附加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何接受多个用空格隔开的用户输入?我不知道输入的数量,但我确实知道它们都是整数.

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.

以下是一些示例输入:

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: '))

但是我正在寻找一种更优雅的解决方案,不需要向用户询问2个问题.

But I am looking for a more elegant solution that doesn't require asking the user 2 questions.

推荐答案

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

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

这篇关于接受python中用空格隔开的多个用户输入,并将它们附加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆