Re: [問題] 列表中依據元素分組

看板Python作者 (逆道者)時間4年前 (2019/12/18 17:37), 編輯推噓1(100)
留言1則, 1人參與, 4年前最新討論串4/4 (看更多)
list_ = ['1A', '7A', '7A-1A', '1A-7A', '1C', '3D', '3B', '3A-7B', '1A-28A-3A','20A-7A-3A', '28A-7A-3A-1A', '7A-3A-1A-28A', '1A-7C-3A', '7B-3A-1A', '3C-7A','7B-3NAV', '3B-7NAV', '20-7', '7'] #設置分數字典 score_dict={ 'A':1, 'B':2, 'C':2, 'D':3, } #建立result字典(空字典) result=dict() #檢查列表中的每個項目 for text in list_: #若含有NAV或者不含有任何分數字典中的key值,則設分數為零 if ('NAV' in text) or all(key not in text for key in score_dict.keys()): score=0 #否則,根據分數字典計算分數 else: score=sum(text.count(key)*value for key,value in score_dict.items()) #更新result字典 result[score]=result.get(score,[])+[text] print(result) 結果: {0: ['7B-3NAV', '3B-7NAV', '20-7', '7'], 1: ['1A', '7A'], 2: ['7A-1A', '1A-7A', '1C', '3B'], 3: ['3D', '3A-7B', '1A-28A-3A', '20A-7A-3A', '3C-7A'], 4: ['28A-7A-3A-1A', '7A-3A-1A-28A', '1A-7C-3A', '7B-3A-1A']} -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.216.6.172 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1576661852.A.D08.html

12/19 14:03, 4年前 , 1F
12/19 14:03, 1F
文章代碼(AID): #1T-VDSq8 (Python)
文章代碼(AID): #1T-VDSq8 (Python)