简体   繁体   English

如何从itertools groupby中提取摘要列表以进行声明

[英]how to extract summary list from itertools groupby for statement

Using python 3.2 In a nested list are two columns of input data: a species code in [0] and an observed value in [1] and from each row two additional columns, [2] and [3], of calculated values, for example: 使用python 3.2在嵌套列表中有两列输入数据:[0]中的种类代码和[1]中的观测值,并且从每一行中分别增加了两列[2]和[3]计算值,用于例:

sorted_trees=[
['ACRU', 5, 1, 10],
['ACRU', 6, 2, 11],
['QURU', 7, 3, 12],
['QURU', 8, 4, 13]]

I needed, and got (with help) the subtotals in [2] and [3] for each species code [0] by: 我需要,并在帮助下获得了每个物种代码[0]的[2]和[3]小计:

import itertools as it, operator as op
for k,g in it.groupby(sorted_trees, key=op.itemgetter(0)):
    tempg=list(g)
    print(k, sum(i[2] for i in tempg), sum(i[3] for i in tempg))

Now I need to make another list, call it summary_trees, with just these values in it so I can use it elsewhere. 现在,我需要制作另一个列表,将其命名为summary_trees,其中仅包含这些值,以便可以在其他地方使用它。 It this example it would be: 这个例子将是:

summary_trees=[[ACRU, 3, 21],[QURU, 7, 25]]

It seems like this should be simple and I feel dumb not to see it. 看来这应该很简单,但我看不见却很蠢。 In real life there is an indeterminate number of species codes, usually between 4-8 在现实生活中,种类代码的数量不确定,通常在4-8之间

It seems as simple as building a list with your printed output... 看起来就像用打印输出建立列表一样简单。

import itertools as it, operator as op
summary_trees = []
for k,g in it.groupby(sorted_trees, key=op.itemgetter(0))
    tempg=list(g)
    summary_trees.append([k, sum(i[2] for i in tempg), sum(i[3] for i in tempg)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM