简体   繁体   English

使用 python 中的文件创建 2D 网格

[英]Creating a 2D grid using a file in python

I am making a grid that is populated with numbers from a txt file.我正在制作一个填充有来自 txt 文件的数字的网格。 The first 2 numbers of the file represent the row and column and the rest are the numbers that will populate my grid.文件的前 2 个数字代表行和列,rest 是将填充我的网格的数字。 Ive attempted to solve this myself but I ve have not been successful.我试图自己解决这个问题,但我没有成功。 Any help or suggestions are greatly appreciated.非常感谢任何帮助或建议。

the file would contain something like this: 2 2 15 20 36 78该文件将包含以下内容:2 2 15 20 36 78

with open('file.txt', 'r') as f: 
    content = f.readlines()
    grid = [] 
    for num in content:
        grid.append(num.split())
    

print(grid)

with my code, I'm only getting [['2'], ['2'], ['15'],['20'], ['36'],['78']] and what I'm looking for is a nested list as such [[15,20],[36,78]]使用我的代码,我只得到 [['2'], ['2'], ['15'],['20'], ['36'],['78']] 和我的m 寻找的是一个嵌套列表,例如 [[15,20],[36,78]]

Thank you in advance for the help.预先感谢您的帮助。

Try the following:尝试以下操作:

content = ["2 2 15 20 36 78"]
grid = content[0].split()
new_lst = []
for num in range(2, len(grid)-1, 2):
    new_lst.append([grid[num], grid[num+1]])
print(new_lst)

Try slight modifications in your code:尝试对您的代码稍作修改:

with open('file.txt', 'r') as f: 
    content = f.readlines()
    line = content[0].split()
    nums = [int(num) for num in line]
    grid = [] 
    for i in range(0, len(nums), 2):
        grid.append(nums[i:i+2])
print(grid)

If you have multiple lines in the file, try this:如果文件中有多行,请尝试以下操作:

grid = []
with open('file.txt', 'r') as f: 
    for line in f:
        line = line.split()
        nums = [int(num) for num in line] 
        for i in range(0, len(nums), 2):
            grid.append(nums[i:i+2])
print(grid)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM