Python basics: how to read N int until '\ n' is found in stdin

How can I read N int from the input and stop reading when I find \n ? Also, how can I add them to an array that I can work with?

I am looking for something like this from C, but in python

 while(scanf("%d%c",&somearray[i],&c)!=EOF){ i++; if (c == '\n'){ break; } } 
+4
source share
2 answers

In Python 2:

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

raw_input() reads a whole line from input (stop at \n ) as a string. .split() creates a list of strings, breaking input into words. map(int, ...) creates integers from these words.

In Python 3, raw_input was renamed to input , and map returns an iterator, not a list, so you need to make a couple of changes:

 lst = list(map(int, input().split())) 
+17
source

There is no direct equivalent to scanf in Python, but this should work

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

In Python3, raw_input been renamed to input

 somearray = map(int, input().split()) 

Here is a breakdown / explanation

 >>> raw=raw_input() # raw_input waits for some input 1 2 3 4 5 # I entered this >>> print raw 1 2 3 4 5 >>> print raw.split() # Make a list by splitting raw at whitespace ['1', '2', '3', '4', '5'] >>> print map(int, raw.split()) # map calls each int() for each item in the list [1, 2, 3, 4, 5] 
+13
source

Source: https://habr.com/ru/post/1301648/


All Articles