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

作者: mantour (朱子)   2016-02-01 01:28:55
※ 引述《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
供參考
作者: busystudent (busystudent)   2016-02-01 15:29:00
感謝解答!

Links booklink

Contact Us: admin [ a t ] ucptt.com