Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a line of integers in Python [duplicate]

Tags:

python

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!

like image 562
kunal18 Avatar asked Apr 12 '13 05:04

kunal18


People also ask

How do you read a line of numbers in Python?

You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python. We read the entire file using this way and then pick specific lines from it as per our requirement. Use readlines()[start:end] to read range of lines.

How do you input a line of integers in Python?

As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.

How do you read two space-separated integers in Python?

Thanks. Easy solution is just to use the string method split. input: 5 8 0 sgshsu 123 input. split(" ") == ["5", "8", "0", "sgshsu", "123"] #Then they are easy to convert to numeric datatypes, but invalid inputs might raise errors.

How do you get two integers from the same line in Python?

In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator.


2 Answers

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()]
like image 141
NPE Avatar answered Oct 08 '22 17:10

NPE


map(int, list) should solve your problem

like image 1
Mayank Jain Avatar answered Oct 08 '22 17:10

Mayank Jain