Re: [問題] 詢問list如行相加
※ 引述《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要去計算,就感到怪怪的,請大家給我提示,謝謝
可以試試collections.Counter 不過首先bookmark_x是數字比較好處理
from collections import Counter
link_a = ['a','b','c']
bookmark_a = [1,2,3]
link_b = ['b','c']
bookmark_b = [4,5]
link_c = ['a']
bookmark_c = [6]
counts = [dict(zip(link_a, bookmark_a)),
dict(zip(link_b, bookmark_b)),
dict(zip(link_c, bookmark_c))]
c = Counter()
map(c.update, counts)
answer_link_all, answer_bookmark_all = zip(*c.iteritems())
print answer_link_all, answer_bookmark_all
如果想用簡單的dict搞定的話 (這邊用collections.defaultdict可以再簡化一點)
total = dict()
for i in range(len(link_a)):
if link_a[i] in total:
total[link_a[i]] += bookmark_a[i]
else:
total[link_a[i]] = bookmark_a[i]
for i in range(len(link_b)):
if link_b[i] in total:
total[link_b[i]] += bookmark_b[i]
else:
total[link_b[i]] = bookmark_b[i]
for i in range(len(link_c)):
if link_c[i] in total:
total[link_c[i]] += bookmark_c[i]
else:
total[link_c[i]] = bookmark_c[i]
answer_link_all = total.keys()
answer_bookmark_all = []
for k in answer_link_all:
answer_bookmark_all.append(total[k])
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.30.46
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1454251540.A.52F.html
※ 編輯: ckc1ark (140.112.30.46), 01/31/2016 22:52:44
→
02/01 01:06, , 1F
02/01 01:06, 1F
我是想試著不用zip讓link和bookmark的idx串在一起 或許用enumerate會好看一點?
或是我要假設zip是入門等級這樣
又或者是你的意思是要用len_a = len(link_a)這樣?
推
02/01 01:18, , 2F
02/01 01:18, 2F
推
02/01 01:21, , 3F
02/01 01:21, 3F
爆炸是不被允許的 我看還有三分鐘 我再做一碗黯然銷魂飯好了
※ 編輯: ckc1ark (140.112.30.46), 02/01/2016 02:06:53
推
02/01 15:37, , 4F
02/01 15:37, 4F
討論串 (同標題文章)