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

2024-10-06 16:19:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

1 3 5 7 9

我尝试过的

  1. arr = input.split(' ')但这不会将它们转换为整数。它创建字符串数组

  2. arr = input.split(' ')

    for i,val in enumerate(arr): arr[i] = int(val)

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


Tags: 字符串in列表forinput整数val数组
3条回答

你可以从下面的程序中得到很好的参考

# The following command can take n number of inputs 
n,k=map(int, input().split(' '))
a=list(map(int,input().split(' ')))
count=0
for each in a:
    if each >= a[k-1] and each !=0:
        count+=1
print(count)

使用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都有效

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

使用list comprehensions
下面是关于ideone的示例:

arr = [int(i) for i in input().split()]

如果您使用的是Python 2,那么应该使用raw_input()

相关问题 更多 >