简体   繁体   中英

Creating a 2D grid using a file in python

I am making a grid that is populated with numbers from a txt file. The first 2 numbers of the file represent the row and column and the rest are the numbers that will populate my grid. 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

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]]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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