在lis中放置一套计数器

2024-09-30 20:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下的结果:

  • 计数器({u'holmes':1,u'heard':1,u'woman':1,u'sherlock:1})
  • 计数器({u'twist':1,u'place':1,u'oliver':1,u'where':1,u'treats:1})
  • 反对({u'worded':1,u'washington':1,u'monday':1,u'democratics:1})

但我想要的是:

my_list = [Counter({u'holmes': 1, u'heard': 1, u'woman': 1, u'sherlock': 1}), Counter({u'twist': 1, u'place': 1, u'oliver': 1, u'where': 1, u'treats': 1}), Counter({u'vowed': 1, u'washington': 1, u'monday': 1, u'democrats': 1})]

为了把它们加起来像Summing list of counters in python

谢谢你的帮助!在


Tags: counter计数器placewherelisttreatssherlockholmes
1条回答
网友
1楼 · 发布于 2024-09-30 20:17:35

把它放在一个列表中,就像你平常对待任何对象一样。在

from collections import Counter

cnt1 = Counter()

cnt2 = Counter()

cnt3 = Counter()

for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
  cnt1[word] += 1

print cnt1

for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
  cnt2[word] += 1

print cnt2

for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
  cnt3[word] += 1

print cnt3

my_list = [cnt1, cnt2, cnt3]

print my_list

这将输出以下内容:

^{pr2}$

相关问题 更多 >