如何读取作为整数除以 space 并分隔到不同行的输入 (txt)

How to read input given as integers divided by space and separated to different lines (txt)

我正在 Python 中进行此编码挑战,在挑战中,输入是在名为 "input.txt" 的文件中以 space 分隔的整数行形式给出的,如下所示:

3 3 1
1 0 3 1
2 2

每一行代表输入的不同部分,例如第一行是网格的宽度和高度以及其中的墙数,第二行是开始和结束的坐标,第三行是特定墙的坐标。 你将如何读取文件,所以最后你会得到一个列表,其中每一行都是列表中的一个单独的项目,如下所示:

input = [[3, 3, 1], [1, 0, 3, 1], [2, 2]]
# the numbers are integers

感谢回答

with open('input.txt', 'r') as infile:
    # iterating through a file will naturally iterate line-by-line
    # str.split() will split on spaces naturally, and we can convert to int for each value
    # thus, a nested list comprehension
    inp = [[int(i) for i in line.split()] 
           for line in infile]