簡體   English   中英

使用 python 中的文件創建 2D 網格

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

我正在制作一個填充有來自 txt 文件的數字的網格。 文件的前 2 個數字代表行和列,rest 是將填充我的網格的數字。 我試圖自己解決這個問題,但我沒有成功。 非常感謝任何幫助或建議。

該文件將包含以下內容: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)

使用我的代碼,我只得到 [['2'], ['2'], ['15'],['20'], ['36'],['78']] 和我的m 尋找的是一個嵌套列表,例如 [[15,20],[36,78]]

預先感謝您的幫助。

嘗試以下操作:

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)

嘗試對您的代碼稍作修改:

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)

如果文件中有多行,請嘗試以下操作:

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