作者ckc1ark (伪物)
看板Python
标题Re: [问题] 询问list如行相加
时间Sun Jan 31 22:45:38 2016
※ 引述《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://webptt.com/cn.aspx?n=bbs/Python/M.1454251540.A.52F.html
※ 编辑: ckc1ark (140.112.30.46), 01/31/2016 22:52:44
1F:→ uranusjr: 谁教你写 for i in range(len(link_a)) 的... 02/01 01:06
我是想试着不用zip让link和bookmark的idx串在一起 或许用enumerate会好看一点?
或是我要假设zip是入门等级这样
又或者是你的意思是要用len_a = len(link_a)这样?
2F:推 CaptainH: 同意楼上…超丑的 02/01 01:18
3F:推 CaptainH: 整篇都丑到爆炸… 02/01 01:21
爆炸是不被允许的 我看还有三分钟 我再做一碗黯然销魂饭好了
※ 编辑: ckc1ark (140.112.30.46), 02/01/2016 02:06:53
4F:推 busystudent: 感谢解答! 02/01 15:37