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

后端 未结 2 865
南旧
南旧 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: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).

提交回复
热议问题