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

该博客讨论了如何在不知道用户将输入多少个整数的情况下,优雅地从用户那里接收多个由空格分隔的整数。示例输入包括一系列整数序列。解决方案包括使用`split()`方法来分隔输入字符串,并通过`map()`或列表推导式将其转换为整数列表。
摘要由CSDN通过智能技术生成

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.

解决方案s = raw_input("Please enter your numbers: ")

mynums = [int(i) for i in s.split()]

# OR

mynums = map(int, s.split())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值