How to read limited number of input separated by space in Python?

后端 未结 2 847
南旧
南旧 2021-01-17 07:00

While coding for competitions in codechef, I face this problem with python, to read

3     # number of required input  
1 4 2 # inputs 
         


        
相关标签:
2条回答
  • 2021-01-17 07:00

    To separate input by spaces:

    data=list(map(int,input().split(' ')))
    

    To verify wether the correct amount of numbers were passed:

    if len(data) > n: # where n is your number of required input
        # Raise an exception or ask for the input again.
    
    0 讨论(0)
  • 2021-01-17 07:18

    You may use list comprehension syntax:

    req_size = int(input().strip())
    data = [int(i) for i in input().strip().split()[:req_size]]
    

    explanation: .strip() method removes \n and oyher whitespace symbols from the start and end of the string. .split() method splits string by any whitespace symbol. If you prefer to split only by whitespaces, use ' ' character explicitly: .split(' '). Split method returns list, and you can use [:req_size] to get firsr req_size elements from it (stabdart list syntax). Then int type applied to your data with list comprehension syntax (shorthand for the for loop).

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