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

看板Python作者 (松鼠)時間4年前 (2019/12/18 17:03), 4年前編輯推噓2(203)
留言5則, 2人參與, 4年前最新討論串3/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分 ------------ 這項需求的關鍵在 計分。 比較好維護的寫法是把計分拉出來寫成一個function。 之後若修改計分規則(例如ABCD權重改變 或者外加別的特殊條件), 只要計分的function隨著修正即可。 可用工具:dictionary, filter, lambda 參考範例:https://www.onlinegdb.com/rJvuhKP0S # compute score for input string def get_score( s:str )->int: if 'NAV' in s: return 0 grade_table = { 'A': 1, 'B': 2, 'C': 2, 'D' : 3} score = 0 for idx, grade in enumerate(grade_table.keys()): score += s.count( grade ) * grade_table[grade] return score if __name__ == '__main__': list_test = ['1A', '7A', ..., 為節約版面,後續元素和原本的敘述相同 ] score_group = [None] * 5 # create score group from 0 to 4 for wanted_score in range(0,5): score_group[wanted_score] \ = list( filter (lambda x: (get_score(x) == wanted_score), list_test) ) # output score group from 0 to 4 for s, g in enumerate(score_group): print( "{score} score list: {group}".format( score = s, group = g) ) ※ 編輯: cuteSquirrel (101.12.103.116 臺灣), 12/18/2019 21:20:09

12/19 14:53, 4年前 , 1F
我的python2.7第一行會出錯,不過還是謝謝指導
12/19 14:53, 1F

12/19 16:01, 4年前 , 2F
把type hint 的語法拿掉就可以在 python 2.7 跑了
12/19 16:01, 2F

12/19 16:01, 4年前 , 3F

12/19 17:00, 4年前 , 4F
謝謝~實際套用結果 https://i.imgur.com/8AZTFwF.jpg
12/19 17:00, 4F

12/19 17:39, 4年前 , 5F
:)
12/19 17:39, 5F
文章代碼(AID): #1T-UjxAr (Python)
文章代碼(AID): #1T-UjxAr (Python)