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!
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.
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.
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.
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.
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()]
map(int, list)
should solve your problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With