15

I am beginner in Python and I am solving a question at CodeChef where I have to read a line of space separated integers. This is what I am doing:

def main():

  t=int(raw_input())    #reading test-cases

  while t!=0:
    n, k=raw_input().split()    #reading a line of two space separated integers
    n, r=int(n), int(r)    #converting them into int
    list=[]
    #reading a line of space separated integers and putting them into a list
    list[-1:101]=raw_input().split()   

Now I to convert each element in the list to integer. Is there some better way to to do this? Please suggest an online resource where I can play with Python and learn tips and tricks!

kunal18
  • 1,935
  • 5
  • 33
  • 58
  • what is the the purpose of t? – jurgenreza Apr 12 '13 at 05:51
  • and why you read two integers and what are you trying to do with `[-1:101]` slice? – jurgenreza Apr 12 '13 at 05:52
  • reading two integers is a part of solution, pay no attention to that. Coming to slice, since I have to read a line of space separated integers and put them into a list, I am using list[-1:101]. There won't be more than 100 numbers. So using this and split(), all numbers (in form of string) are stored in the list. – kunal18 Apr 12 '13 at 06:01

2 Answers2

42

In Python 2, you could write:

numbers = map(int, raw_input().split())

This reads a line, splits it at white spaces, and applies int() to every element of the result.

If you were using Python 3, the equivalent expression would be:

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

or

numbers = [int(n) for n in input().split()]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

map(int, list) should solve your problem

Mayank Jain
  • 2,504
  • 9
  • 33
  • 52