用于单行列表输入和多行数组inpu的Python代码

2024-09-29 17:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有没有什么方法可以在Python中接受单行和多行的列表输入? 和C++一样,我们有:-

for(i=0;i<5;i++)
{
  cin>>A[i]; //this will take single line as well as multi-line input .
}

现在在Python中我们有:

^{pr2}$ 我的问题是,我们是否有任何Python代码,可以在C++中使用单行和多行输入?在


Tags: 方法列表forinputaslinethismulti
2条回答

根据文档,^{}读取一行。在

多行“输入”的最小示例。在

>>> lines = sys.stdin.readlines() # Read until EOF (End Of 'File'), Ctrl-D
1 # Input
2 # Input
3 # Input. EOF with `Ctrl-D`.
>>> lines # Array of string input
['1\n', '2\n', '3\n']
>>> map(int, lines) # "functional programming" primitive that applies `int` to each element of the `lines` array. Same concept as a for-loop or list comprehension. 
[1, 2, 3]

如果您不喜欢使用map,请考虑使用列表压缩:

^{pr2}$

重新发明方形车轮很容易:

def m_input(N):
    if(N < 1): return []
    x = input().strip().split()[:N]
    return x + m_input(N - len(x))

相关问题 更多 >

    热门问题