Python basics: How to read N ints until '\n' is found in stdin

有些话、适合烂在心里 提交于 2020-12-29 07:00:06

问题


How can I read N ints 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'm looking for something like this from C but in python

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

回答1:


In Python 2:

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

raw_input() reads a whole line from the input (stopping at the \n) as a string. .split() creates a list of strings by splitting the input into words. map(int, ...) creates integers from those words.

In Python 3 raw_input has been renamed to input and map returns an iterator rather than a list, so a couple of changes need to be made:

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



回答2:


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

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

In Python3 raw_input has 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]


来源:https://stackoverflow.com/questions/2285284/python-basics-how-to-read-n-ints-until-n-is-found-in-stdin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!