用于单行列表输入以及多行数组输入的 Python 代码



我们是否有任何可以在 Python 中进行单行和多行列表输入? 就像C++我们有:-

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

现在在Python中,我们有:-

l=list(map(int,input().strip().split())) //for single line 
&
l=list()
for i in range of(0,5):
x=int(input())
l.append(x) //for multi-line input

所以我的问题是,我们是否有任何 python 代码可以接受单行和多行输入,就像我们在C++一样?

根据文档,input()读取一行。

具有多行"输入"的最小示例。

>>> 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
['1n', '2n', '3n']
>>> 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,请考虑列表压缩:

>>> [int(l) for l in lines]
[1, 2, 3]

重新发明方轮很容易:

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

最新更新