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

前端 未结 4 762
情深已故
情深已故 2020-11-30 09:37

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

相关标签:
4条回答
  • 2020-11-30 09:49

    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)
    
    0 讨论(0)
  • 2020-11-30 09:59

    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.

    0 讨论(0)
  • 2020-11-30 10:04

    You can try this below code that takes an input from user and reads it as array and not list.

    from array import *
    a = array('i',(int(i) for i in input('Enter Number:').split()))
    print(type(a))
    print(a)
    

    IN addition , if you wish to convert it to a list:

    b = a.tolist()
    print(type(b))  
    print(b)
    
    0 讨论(0)
  • 2020-11-30 10:15

    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

    0 讨论(0)
提交回复
热议问题