How to read an array of integers from single line of input in python3

送分小仙女□ 提交于 2019-12-28 06:34:08

问题


I want to read an array of integers from single line of input in python3. For example: Read this array to a variable/list

1 3 5 7 9

What I have tried

  1. arr = input.split(' ') But this does not convert them to integers. It creates array of strings

  2. arr = input.split(' ')

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

2nd one is working for me. But I am looking for an elegant(Single line) solution.


回答1:


Use map:

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

Just adding, in Python 2.x you don't need the to call list(), since map() already returns a list, but in Python 3.x "many processes that iterate over iterables return iterators themselves".

This input must be added with () i.e. parenthesis pairs to encounter the error. This works for both 3.x and 2.x Python




回答2:


Edit: After using Python for almost 4 years, just stumbled back on this answer and realized that the accepted answer is a much better solution.

Same can be achieved using list comprehensions:
Here is example on ideone:

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

If you are using Python 2, you should use raw_input() instead.




回答3:


You can get a good reference from the following program

# 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)


来源:https://stackoverflow.com/questions/18332801/how-to-read-an-array-of-integers-from-single-line-of-input-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!