首页 > 解决方案 > 如何在python中将整数动态二维数组作为输入(在线IDE)

问题描述

我想在未定义行数和列数的在线编译器中将一个自由大小的二维数组作为用户在 python 中的输入。

For example if the input is :

1 2 3 4
5 6 7
8 9
10
11 12 13 14 15

I want to store it like [[1,2,3,4],[5,6,7],[8,9],[10],[11,12,13,14,15]]

标签: pythonpython-3.xmultidimensional-arrayinputdynamic

解决方案


您应该知道,当代码中有过多的输入语句但没有输入考虑到这一点时,在线 IDE 会抛出 EOF 错误我们可以在在线 IDE 中进行动态输入。

matrix = []
while True:
    try:
        matrix.append(list(map(int,input().split())))
    except:
        break

您可以通过在每个新行的末尾也知道进位返回来做到这一点,除了最后一行之外,您将有进位返回 ('\r')

matrix = []
while True:
    row = input()
    matrix.append(row.strip())
    print(row)
    if row[-1] != '\r':
        break


推荐阅读