python中的list中多个有包含tuple的list,如何将每个list中的tuple的对应元素相加?
tagged_list=[[('I',0),('feel',0.2),('happy',0.8),('and',0),('excited',0.4),('today',0...
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的值,求大神指点 展开
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的值,求大神指点 展开
1个回答
展开全部
我用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)
第三个就是
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询