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

看板Python作者 (迅雷不及掩耳盜鈴)時間5年前 (2019/12/18 17:03), 編輯推噓2(200)
留言2則, 2人參與, 5年前最新討論串2/4 (看更多)
※ 引述《radiant77 (七七)》之銘言: : 有一個列表,長度非固定,其中有A、B、C、D、NAV等字 : 希望依據總分放到不同的list中,只看英文字母,前面的數字不算分 : A = 1分 : B = 2分 : C = 2分 : D = 3分 : NAV或0分的一組 : 例如:'7A-1A'有兩個A,就是1+1=2分,'1C', '3B'也都是2分 : '1A-7C-3A',就是1+2+1=4分,'28A-7A-3A-1A'是1+1+1+1=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'] : 依照總分排序後的新列表如下: : 1分 : list_1 = ['1A', '7A'] : 2分 : list_2 = ['7A-1A', '1A-7A', '1C', '3B'] : 3分 : list_3 = ['3D', '3A-7B', '1A-28A-3A', '20A-7A-3A', '3C-7A'] : 4分 : list_4 = ['28A-7A-3A-1A', '7A-3A-1A-28A', '1A-7C-3A', '7B-3A-1A'] : 其他: list_NAV = ['7B-3NAV', '3B-7NAV', '20-7', '7'] : ---------------------------------------- : 我之前只有分到2分,用的方法比較簡單,無法對應更多的分數 : 希望能直接依據總分來分組,以後要計算5.6.7分的話可以方便新增 : 以下是我之前用的方法: : 1分 list_1 = [i for i in list if i.count('A') and not i.count('-')] : 2分 list_2 = [i for i in list if i.count('A') <> 1 and not i.count('-') == 2] : 還請前輩看看,謝謝! 如果是我會這樣做: ```python # import defaultdict for dictionary appending from collections import defaultdict result = defaultdict(list) # define char-score pair and scores calculating function char_score = {'A': 1, 'B': 2, 'C': 2, 'D': 3} calculate_score = lambda string: sum([string.count(k) * v for k, v in char_score.items()]) # traverse and create score_list words = ['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'] for word in words: if 'NAV' in word or calculate_score(word) == 0: result['NAV'].append(word) else: result[calculate_score(word)].append(word) ``` -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.247.1 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1576659783.A.1DA.html

12/18 18:50, 5年前 , 1F
12/18 18:50, 1F

12/19 13:32, 5年前 , 2F
非常感謝 結果符合預期 https://imgur.com/L7tI76o.jpg
12/19 13:32, 2F
文章代碼(AID): #1T-Uj77Q (Python)
文章代碼(AID): #1T-Uj77Q (Python)