继续调用input() 函数,直到它读入的行为空。使用 .split 方法(无 args = 空格作为分隔符)。使用 list-comp 将每个 string 转换为 int 并将其附加到您的 examList。
代码如下:
examList = []
i = input()
while i != '':
examList.append([int(s) for s in i.split()])
i = input()
根据您的意见,examList 是:
[[3], [2, 1], [1, 1, 0], [2, 1, 1], [4, 3, 0, 1, 2], [2], [1, 2], [1, 3]]
上述方法适用于Python3,它允许您调用input() 并且不输入任何内容(这就是为什么我们使用它作为一个信号来检查我们是否完成了 - i != '')。
但是,从the docs,我们看到,在Python2 中,input() 的空条目会引发EOF 错误。为了解决这个问题,我想我们可以做到这一点,以便在输入以下字符串时结束多行输入:END。这意味着您必须使用 'END' 来停止输入:
examList = []
i = raw_input()
while i != 'END':
examList.append([int(s) for s in i.split()])
i = raw_input()
请注意,我使用 raw_input 来不执行类型转换。
其工作原理与上述相同。