【发布时间】:2010-02-17 23:35:09
【问题描述】:
如何从输入中读取 N 个ints,并在找到\n 时停止读取?另外,如何将它们添加到我可以使用的数组中?
我正在从 C 语言中寻找类似的东西,但在 python 中
while(scanf("%d%c",&somearray[i],&c)!=EOF){
i++;
if (c == '\n'){
break;
}
}
【问题讨论】:
如何从输入中读取 N 个ints,并在找到\n 时停止读取?另外,如何将它们添加到我可以使用的数组中?
我正在从 C 语言中寻找类似的东西,但在 python 中
while(scanf("%d%c",&somearray[i],&c)!=EOF){
i++;
if (c == '\n'){
break;
}
}
【问题讨论】:
在 Python 2 中:
lst = map(int, raw_input().split())
raw_input() 从输入中读取整行(在\n 处停止)作为字符串。
.split() 通过将输入拆分为单词来创建字符串列表。
map(int, ...) 从这些单词中创建整数。
在 Python 3 中,raw_input 已重命名为 input,map 返回的是迭代器而不是列表,因此需要进行一些更改:
lst = list(map(int, input().split()))
【讨论】:
Python 中没有直接等效的 scanf,但这应该可以工作
somearray = map(int, raw_input().split())
在 Python3 中,raw_input 已重命名为 input
somearray = map(int, input().split())
这是一个细分/解释
>>> 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]
【讨论】: