【问题标题】:Group list items according to digit counts in second list根据第二个列表中的位数对列表项进行分组
【发布时间】:2019-05-05 03:40:46
【问题描述】:

目标是创建一个堆叠条形图,显示总共 360 秒(以秒为单位)的推文(我从 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 之外,我宁愿不使用任何库。

【问题讨论】:

  • 用list2计算列表1中的项目这是什么意思?
  • 啊,我想我现在明白了。
  • @timgeb list2 是每分钟保存多少条推文的计数。所以要知道每秒保存了多少 pos/neg/neu 推文,我需要list2
  • 因为list2 表示第一秒有 2 条推文,这意味着list1 中的第一个两个值。因此,OP 所需的输出在 pos 和 neg 列表中显示 1 和 1
  • 明白了,我想我可以想出一个算法。

标签: python list matplotlib graph


【解决方案1】:

代码:

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

【讨论】:

  • 谢谢,看起来很整洁。是否有可能在不导入任何库等的情况下解决问题? 编辑 看到它们是标准的,我将为我的代码尝试这种方法。谢谢
  • @Aileen 是的,但是在我编写一个不使用标准库的笨重实现之前,你能告诉我为什么吗?
  • 这个问题是更大的 uni assignment 的一部分,我们不允许使用 matplotlib 以外的库。这就是为什么我一直在寻找一种使用简单 for 循环等的方法。
  • 是的,但是 matplotlib 从标准库(以及使用 numpy)强烈导入。
  • @Aileen 我明白了。我添加了一个无导入解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 2011-05-21
  • 2022-08-16
  • 1970-01-01
相关资源
最近更新 更多