【问题标题】:How to read input given as integers divided by space and separated to different lines (txt)如何读取以整数除以空格并分隔为不同行的输入(txt)
【发布时间】:2020-05-26 03:09:28
【问题描述】:

我在 Python 中进行这个编码挑战,在挑战中,输入是在名为“input.txt”的文件中以空格分隔的整数行给出的,如下所示:

3 3 1
1 0 3 1
2 2

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

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

感谢回答

【问题讨论】:

  • 逐行读取文件,在空格上分割每一行,将每个元素解析为整数,添加到列表中

标签: python list input file-read


【解决方案1】:
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]

【讨论】:

    猜你喜欢
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2019-07-09
    • 1970-01-01
    相关资源
    最近更新 更多