楼主:
ckc1ark (伪物)
2016-01-31 22:45:38※ 引述《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])