如何从python3中的单行输入读取整数数组

问题描述 投票:4回答:2

我想从python 3中的单行输入读取一个整数数组。例如:将此数组读取到变量/列表

1 3 5 7 9

What I have tried

  1. arr = input.split(' ')但这不会将它们转换为整数。它创建字符串数组
  2. arr = input.split(' ') for i,val in enumerate(arr): arr[i] = int(val)

第二个是为我工作。但我正在寻找一个优雅的(单线)解决方案。

python arrays list input python-3.2
2个回答
21
投票

使用map

arr = list(map(int, input().split()))

只是添加,在Python 2.x中你不需要调用list(),因为map()已经返回一个list,但在Python 3.x "many processes that iterate over iterables return iterators themselves"中。

必须使用()即括号对添加此输入以遇到错误。这适用于3.x和2.x Python


5
投票

编辑:使用Python近4年后,只是偶然发现了这个答案,并意识到接受的答案是一个更好的解决方案。

使用qazxsw poi可以实现同样的效果: 这是qazxsw poi的例子:

list comprehensions

如果您使用的是Python 2,则应使用ideone

© www.soinside.com 2019 - 2024. All rights reserved.