簡體   English   中英

從 Python 中的 a.txt 文件創建方陣

[英]Creating a square matrix from a .txt file in Python

我即將為 TSP(對稱)問題創建一個運行哈密頓循環的程序,這意味着路徑只到達一個點,然后走得更遠。 這些點之間的距離可以寫成方陣。 因為問題是對稱的,所以我只有這個矩陣的一半作為.txt文件

我需要創建一個程序,它允許我將由空格分隔的值從 a.txt 文件插入到數組中,並從中創建一個對稱的方陣。

URL 在 .txt 文件中查看當前的想法和數據布局:

https://imgur.com/4G3sXrp

我是 Python 的新手,我真的不明白如何在這個級別上使用 IO。

我試過使用 numpy function: loadtxt 但對我不起作用,我收到一條錯誤消息,說我無法將字符串轉換為浮點數

我還嘗試通過創建應該拆分文本並創建此矩陣的循環來進行操作。

def createMatrix(rows):
    matrix= [[0 for col in range(int(rows[0]))] for row in range(int(rows[0]))]
    i = 0
    for w in rows[1:]:
        w = string.strip(w).split(' ')
        j = 0
        for dist in w:
            matrix[i][j] = int(dist)
            matrix[j][i] = int(dist)
            j+=1
        i+=1
 return matrix

我希望代碼結果至少能以某種方式指導我應該做什么,但正如我所提到的,我是一個新手,我真的不知道如何開始處理這個特定問題。

在您鏈接到的圖片中,顯示了您希望矩陣的外觀,最后一列有 12 兩次。 此外,在倒數第二列中,您得到了 19。嗯? 此外,輸入文本文件的最后兩行/行都有五個數字。 我猜最后一行應該有六個數字。

數字具有不同位數的事實使得直觀地驗證一切是否正確變得更加困難。

如果您有一個看起來像這樣的文本文件(“stuff.txt”)(注意,填充的前導零):

00
01 00
02 03 00
04 05 06 00
07 08 09 10 00
11 12 13 14 00

和代碼:

with open("stuff.txt", "r") as file:
    lines = list(map(str.split, file.read().splitlines()))

    missing_values = []

    for index in range(len(lines)):
        missing_values.append([line[index] for line in lines[index+1:]])

    matrix = [line + values for line, values in zip(lines, missing_values)]

    for row in matrix:
        print(row)

Output:

['00', '01', '02', '04', '07', '11']
['01', '00', '03', '05', '08', '12']
['02', '03', '00', '06', '09', '13']
['04', '05', '06', '00', '10', '14']
['07', '08', '09', '10', '00', '00']
['11', '12', '13', '14', '00']

矩陣不是正方形的,因為文本文件中的最后兩行有五個數字(最后一行應該有六個)。

您可以使用np.tril_indices填充最終方陣的下三角部分,然后使用M += MT填充 rest (因為您的對角線為零):

import numpy as np

with open('/tmp/test.txt') as fh:
    data = np.fromstring(fh.read().replace('\n', ' '), dtype=int, sep=' ')

n = int(np.sqrt(8*data.size + 1) - 1) // 2
matrix = np.zeros((n, n), dtype=int)
matrix[np.tril_indices(len(matrix))] = data
matrix += matrix.T  # Only works if diagonal is zero.

print(matrix)

使用 OP 的示例數據進行測試:

text = '''0
1 0
2 3 0
4 5 6 0
7 8 9 10 0
11 12 13 14 15 0'''

with open('/tmp/test.txt', 'w') as fh:
    fh.write(text)

我們得到 output:

[[ 0  1  2  4  7 11]
 [ 1  0  3  5  8 12]
 [ 2  3  0  6  9 13]
 [ 4  5  6  0 10 14]
 [ 7  8  9 10  0 15]
 [11 12 13 14 15  0]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM