根据第二个列表中的位数对列表项进行分组

时间:2018-12-03 19:32:30

标签: python list matplotlib graph

目标是创建一个堆叠的条形图,以显示总共360秒(以秒为单位)的tweet(我从tweepy得到的)情绪。我有两个清单。第一个按时间顺序对推文进行情感分析,第二个按时间顺序对每秒的推文量进行分析。

list1 = ("neg", "pos", "pos", "neu", "neg", "pos", "neu", "neu",...)
list2 = (2, 1, 3, 2,...)

现在,我想创建某种嵌套循环,并使用list2来计算列表1中的项目。然后,我将拥有3个列表,其中每个可用于图形的情感具有360个值。它应该给我类似以下的输出:

lis_negative = (1, 0, 1, 0, ...)
lis_positive = (1, 1, 1, 0, ...)
lis_neutral = (0, 0, 1, 2, ...)

如何创建此循环,也许有更简单的方法吗?我宁愿不使用除matplotlib之外的任何库。

1 个答案:

答案 0 :(得分:2)

代码:

from itertools import islice
from collections import Counter

def categorize(clas, amounts):
    cats = {'neg': [], 'pos': [], 'neu': []}
    clas = iter(clas)

    for a in amounts:
        cs = Counter(islice(clas, a)) # take a items
        for cat in cats:
            cats[cat].append(cs[cat])
    return cats

演示:

>>> t1 = ('neg', 'pos', 'pos', 'neu', 'neg', 'pos', 'neu', 'neu')
>>> t2 =  (2, 1, 3, 2)
>>> 
>>> categorize(t1, t2)
{'neg': [1, 0, 1, 0], 'neu': [0, 0, 1, 2], 'pos': [1, 1, 1, 0]}

根据要求,提供不导入的解决方案:

def make_counter(iterable):
    c = {}
    for x in iterable:
        c[x] = c.get(x, 0) + 1
    return c

def categorize(clas, amounts):
    cats = {'neg': [], 'pos': [], 'neu': []}
    pos = 0

    for a in amounts:
        chunk = clas[pos:pos+a]
        pos += a
        cs = make_counter(chunk)
        for cat in cats:
            cats[cat].append(cs.get(cat, 0))
    return cats

编辑:更短的无进口解决方案:

def categorize(clas, amounts):
    cats = {k:[0]*len(amounts) for k in ('neg', 'pos', 'neu')}
    pos = 0

    for i, a in enumerate(amounts):
        chunk = clas[pos:pos+a]
        pos += a
        for c in chunk:
            cats[c][i] += 1

    return cats