Re: [問題] 詢問list如行相加

看板Python作者 (朱子)時間8年前 (2016/02/01 01:29), 8年前編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/6 (看更多)
※ 引述《busystudent (busystudent)》之銘言: : hi 我想詢問list若有重複的標籤該如何相加 : 我有三組list,內容為個人所收藏的標籤與其收藏次數,如下所示: : link_a = ['a','b','c'] : bookmark_a = ['1','2','3'] : link_b = ['b','c'] : bookmark_c = ['4','5'] : link_c = ['a'] : bookmark_c = ['6'] : 我想做些計算,得到如下面的結果 : answer_link_all = ['a','b','c'] : answer_bookmark_all = ['7','6','8'] : 其實我一開始是打算 link_a+link_b = ['a','b','c','b','c']後來發現,名稱會 : 重複,像是重複出現'b'和'c'之類的,所以打算寫一個if判斷式,可是考慮到又 : 有bookmark要去計算,就感到怪怪的,請大家給我提示,謝謝 先轉換成 dict , 再用set合併重複的key link_a = ['a','b','c'] bookmark_a = ['1','2','3'] link_b = ['b','c'] bookmark_b = ['4','5'] link_c = ['a'] bookmark_c = ['6'] dict_a = dict(zip(link_a,bookmark_a)) dict_b = dict(zip(link_b,bookmark_b)) dict_c = dict(zip(link_c,bookmark_c)) def count(x): return sum([ int(dic.get(x,0)) for dic in [dict_a,dict_b,dict_c]]) answer_link_all = list(set(link_a+link_b+link_c)) answer_link_all.sort() answer_bookmark_all = [ str(count(key)) for key in answer_link_all ] print answer_link_all print answer_bookmark_all 供參考 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.125.138 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1454261343.A.8D0.html ※ 編輯: mantour (140.112.125.138), 02/01/2016 01:34:56

02/01 15:29, , 1F
感謝解答!
02/01 15:29, 1F
文章代碼(AID): #1MhaHVZG (Python)
討論串 (同標題文章)
文章代碼(AID): #1MhaHVZG (Python)