python中的list中多个有包含tuple的list,如何将每个list中的tuple的对应元素相加?

tagged_list = [[('I',0),('feel',0.2),('happy',0.8),('and',0),('excited',0.4),('today',0)],[('I',0),('feel',0),('happy',1),('and',0),('excited',1),('today',0)],[('I',0),('feel',0),('happy',1),('and',0),('excited',1),('today',0)]]
d ={}
for word_list in tagged_list:
for (word, score) in word_list:
if word in d:
d[word] = d[word] + int(score)
else:
d[word] = d.setdefault(word, 0) + int(score)
print map(tuple, d.items())
代码如上 ,但是得到的list没有加上第一个list的值,求大神指点

我用Python3,最后一行稍微改了一下,执行了看,加上了呀

tagged_list = [[('I',0),('feel',0.2),('happy',0.8),('and',0),('excited',0.4),('today',0)],[('I',0),('feel',0),('happy',1),('and',0),('excited',1),('today',0)],[('I',0),('feel',0),('happy',1),('and',0),('excited',1),('today',0)]]
d ={}
for word_list in tagged_list:
    for (word, score) in word_list:
        if word in d:
            d[word] = d[word] + int(score)
        else:
            d[word] = d.setdefault(word, 0) + int(score)
print(*map(tuple, d.items()))

执行结果

('and', 0) ('today', 0) ('I', 0) ('feel', 0) ('excited', 2) ('happy', 2)

第三个就是

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答