簡體   English   中英

Python-將未知數據加載為n維矩陣

[英]Python - load unknown data as n-dim matrix

我有一個數據文件,其中包括一個未知棋盤游戲的“快照”,例如tictactoe / dama / chess / go..etc。 但是我不知道游戲的參數,例如棋盤的尺寸,棋子的類型等等。

最簡單的情況是抽動,所以以它為例。 件和空白字段用數字(-n,-n + 1 .. 0,+ n-1 .. + n ..)表示

開始:

  • 0 0 0
  • 0 0 0
  • 0 0 0

在這種簡單情況下,每次移動(x,O用1或-1表示,空字段為0。)。 最后,我將得到一組由兩個空行分隔的3x3矩陣。

我如何將數據讀入ndim數組 ([length_of_game] [board_width] [board_length], 而無需手動添加有關游戲的口徑/長度的信息)

我只知道我的棋盤尺寸未知,不同的棋子用不同的數字表示,而快照則表示游戲的發展。

您可以執行此操作的一種方法是逐行分析文件。 將行用空格分隔(假設一行中的數字由空格分隔),然后將結果列表添加到將容納所有行(行數據)的另一列表中(稱為此current_game)。 當您遇到空白行時,可以將current_game列表添加到另一個列表中(讓我們將其稱為一個游戲),該列表將容納所有游戲。

這是一個示例函數,它將執行此操作:

def parse_data_file(file_path):
    games = []
    current_game = []
    with open(file_path, mode='r',) as file_reader:
        for line in file_reader:
            if len(line.strip()) == 0:
                if len(current_game) > 0:
                    # A empty new line, so the current game has finished. Add the current game to the games.
                    games.append(current_game)
                    current_game = []
            else:
                current_game.append(line.strip().split())

    return games

該函數正在檢查當前行的長度是否大於0,如果大於0,則首先將其剝離(從行尾刪除任何空白),然后按空白將其分割。 您可以在此處閱讀有關split函數的更多信息。 如果行長等於0,並且current_game長度大於0(此檢查是僅在游戲列表中添加current_game一次),則它將列表添加到游戲列表中,並將其設置為新的空白名單。

如果要將列表中的字符串轉換為整數,可以在分割線時使用map函數。 這是將字符串轉換為整數的相同代碼:

def parse_data_file(file_path):
    games = []
    current_game = []
    with open(file_path, mode='r',) as file_reader:
        for line in file_reader:
            if len(line.strip()) == 0:
                if len(current_game) > 0:
                    # A empty new line, so the current game has finished. Add the current game to the games.
                    games.append(current_game)
                    current_game = []
            else:
                current_game.append(map(lambda item: int(item), line.strip().split()))

    return games

最后,要將列表轉換為numpy ndim數組,可以使用numpy中的array函數。 該解決方案假定在上一場比賽之后會有兩個空行,但是很容易更改。

暫無
暫無

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

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