Re: [問題] c語言的array轉換成list

看板Python作者 (亮)時間12年前 (2013/08/16 01:20), 編輯推噓1(101)
留言2則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《neurone (明月照大江)》之銘言: : input = : {{ ITEM_I, : 3, : { 0x01, 0x02,0x03}}, : { ITEM_II, : 3, : { 0x11, 0x12,0x13}}, : }; : output = [ ["ITEM_I","3","0x01,0x02,0x03"],[ITEM_II, "3", "0x01,0x02,0x03"]] 原文恕刪,這有另一種解法是實作一個簡單的 Lexer, 但以下的解法比較簡單,其實就是用 regex 硬解,提供您作參考。 如果 pattern 比您舉的更複雜,可能用 Lexer 來處理反而會比較容易 可以搜尋 Lexer, Token, python re 等關鍵字 # parser.py import re txt = open('raw.h').read() # parse the variable assignment # e.g., var = { ... } var_name, var_value = re.search( '(\w+)\s*=\s*\{(.*)\};', # regex pattern txt, # input string re.DOTALL # '.' also matches '\n' ).groups() # a tuple with matched string in each (...) pattern def clean(item): '''trim spaces between comma for 3rd entry of item''' cleaned = list(item) # convert from tuple to mutable list cleaned[-1] = ','.join(entry.strip() for entry in cleaned[-1].split(',')) return cleaned # parse the item array # e.g., { ITEM_XXX, 000m, { ... }}, # then clean the { ... } part, no space between comma l = [clean(item) for item in re.findall('\{\s*(\w+),\s*(\d+),\s*\{([^}]*)\}\},', var_value)] print(var_name, "=", l) ## 執行結果,把「input ...」那段文字存入 raw.h 中 In [1]: %run parser.py input = [['ITEM_I', '3', '0x01,0x02,0x03'], ['ITEM_II', '3', '0x11,0x12,0x13']] -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.230.117.109 修增註解 ※ 編輯: ccwang002 來自: 61.230.117.109 (08/16 01:24)

08/16 11:37, , 1F
請問若array內的element 長度不一樣 可以這樣做嗎?
08/16 11:37, 1F

08/16 11:38, , 2F
我先試試看好了,感謝!
08/16 11:38, 2F
如果是有不同多組的 ITEM_xx array 這個程式不需要更動,ex 現在2組 -> 3, 4, ... ※ 編輯: ccwang002 來自: 61.230.162.248 (08/17 00:03)
文章代碼(AID): #1I3GtW3C (Python)
討論串 (同標題文章)
文章代碼(AID): #1I3GtW3C (Python)