【问题标题】:Lists aggregation in python [duplicate]在python中列出聚合[重复]
【发布时间】:2014-03-15 19:36:57
【问题描述】:

我已经尝试了一段时间来解决以下问题: 我有以下格式的列表:

[[u'unicode_text', 5, 395, 2, 0, 2 .. n], 
 [u'unicode_text', 235, 5, 3, 3, 10 .. n], 
 [u'other_unicode_text', 3, 65, 28, 16, 52 .. n],
 ...
 [u'unicode_text', 95, 5, 8, 7, 38 .. n]]

我正在尝试创建一个新列表,其中将包含由列表中的文本元素分组的数字的总和。上面的结果将如下所示:

[[u'unicode_text', 335, 405, 13, 10, 50 .. n],
 [u'other_unicode_text', 3, 65, 28, 16, 52 .. n]]

我尝试了很多方法,但无法找到一个优雅的解决方案。 Zip 不适用于 unicode 文本,而 itertools groupby 则适用于字典。

【问题讨论】:

  • itertools.groupby 适用于任何可迭代对象。
  • OrderedDict 有效,但它给了我一个分组列表的列表。还有其他方法吗(不像 ['txt', [2,3]] 而是 ['txt', 2, 3])。我可能会错过一些东西。谢谢
  • 你可以使用:['txt'] + [2, 3]

标签: python list


【解决方案1】:

由于每个子列表中的第一项数据为keyed,因此字典是更好的输出容器,您可以执行以下操作:

import operator

output = dict()
container =  [[u'unicode_text', 5, 395, 2, 0, 2],
              [u'unicode_text', 235, 5, 3, 3, 10],
              [u'other_unicode_text', 3, 65, 28, 16, 52],
              [u'unicode_text', 95, 5, 8, 7, 38]]

for sublist in container:
    try:
        output[sublist[0]] = map(operator.add, output[sublist[0]], sublist[1:])
    except KeyError:
        output[sublist[0]] = sublist[1:]

这是一个非常简单的方法,如果这是我们第一次看到一个键,那么我们设置只是将值设置为列表,否则我们将每个值相加并存储新的求和列表,给出:

{ u'other_unicode_text': [3, 65, 28, 16, 52], 
  u'unicode_text':       [335, 405, 13, 10, 50] }

【讨论】:

    【解决方案2】:

    如果你已经安装了pandas,那就很简单了:

    In [5]: d=[[u'uicode_text', 5, 395, 2, 0, 2  ], 
       ...:  [u'uicode_text', 235, 5, 3, 3, 10  ], 
       ...:  [u'other_uicode_text', 3, 65, 28, 16, 52  ],
       ...:  [u'uicode_text', 95, 5, 8, 7, 38  ]]
    
    In [6]: import pandas as pd
       ...: df=pd.DataFrame(d)
       ...: print df.groupby(0).sum()
                         1    2   3   4   5
    0                                      
    other_uicode_text    3   65  28  16  52
    uicode_text        335  405  13  10  50
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 2016-02-14
      • 2018-03-02
      • 2021-05-28
      • 1970-01-01
      • 2020-12-19
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多