看板 Python 關於我們 聯絡資訊
標題下的有點爛,請見諒QQ 我有一個檔案格式長這樣 [gender] Male Female [birthplace] Taipei Taoyuan Taichung Kaohsiung [other] music movie read basketball 我想將他做排列組合,我是這樣寫的 parser = SafeConfigParser(allow_no_value=True) parser.read('twiwan') taiwan = [] g = globals() total_section = parser.sections() for sSection in total_section: g['{0}'.format(sSection)] = [] for item in parser.items(sSection): g[sSection].append(item[0]) for combination in itertools.product(gender, birthplace): for i in xrange(1, len(other) + 1): t = list(combinations(other, i)) for element in t: twiwan.append(list(combination) + list(element)) 這裡有兩個地方寫的不夠好,第一個是我動態產生list的方式 g['{0}'.format(sSection)] = [] 即便不影響正確性,但是他會重複執行 第二個地方是 for combination in itertools.product(gender, birthplace) 因為目前只有gender跟birthplace 如果將來要新增一個新的section [education] phD master 那我勢必要回頭改這個for迴圈改成 for combination in itertools.product(gender, birthplace,education) 請問我可以從那個方向來著手呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.177.7.3 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1506347445.A.B75.html
withoutshine: 想辦法生出 args=(gender, birthplayce, education) 09/25 22:06
withoutshine: 可以呼叫 itertools.product(*args) 09/25 22:06
numpy: 推樓上 09/29 01:38
s860134: unpacking 是 python 很方便的用法 09/29 08:46