Python在列表中添加数字

时间:2014-07-24 09:14:09

标签: python list count add

任何人都可以帮我这些吗? 基本上我有列表开始创建如下所示:

>>> item
[('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]

我想只在满足苹果和人口等时才能合并对象的结果。这是我想要的最终结果:

>>> item
[('apple', 16, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]

任何帮助将不胜感激。

我的错,如果问题不清楚:这是我的一些代码。

def add(par):
    temp_dict = {}
    for name, count, term in par:
            if name in temp_dict:
                    temp_dict[name] += count
            else:
                    temp_dict[name] = count
    result = []
    for name, count, term in par:
            if name in temp_dict:
                    result.append((name, temp_dict[name], term)) 
                    del temp_dict[name]
    return result

如何对班级进行修改,以便返回所需的结果? 上面的代码仍然添加" apple"在一起,这就是:

  
    
      

项           [(' apple',19,' disease'),(' orange','')

    
  

2 个答案:

答案 0 :(得分:2)

您可以按如下方式获得所需的结果:

In [6]: my_items = [('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]

In [7]: import collections

In [8]: my_counter = collections.defaultdict(int)

In [9]: for i in my_items:
    # at this point, i is a tuple, let's unpack it
    (fruit, n, category) = i
    # use the tuple (fruit, category) as a key.
    # note that this has to be a tuple, and not a list
    my_counter[(fruit, category)] += n
   ...:

In [10]: my_counter
Out[10]: defaultdict(<class 'int'>, {('orange', 'population'): 6, ('apple', 'population'): 16, ('apple', 'disease'): 3})

(请注意,这是一个IPython会话,我强烈推荐它使用vanilla shell进行交互式工作)

在此示例中,my_counter是修改后的dict对象。它与“常规”dict的不同之处在于,如果指定的键不可用,将自动创建默认值(在我们的示例中为整数零)。 从您的示例中我了解到您是Python的新手。如果您需要更多聚合功率来处理大量数据,您可能需要查看Pandas

祝你好运。

编辑为了完整起见,在keiminaanswer in this thread之后,您可以考虑使用collections.Counter most_common()多个features that are useful for counters,例如{{1}}这对我来说很新鲜。

答案 1 :(得分:2)

您也可以使用collections.Counter。当你数数时,它很有用。

from collections import  Counter
item = [('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]

c = Counter()
for name, count, term in item:
    c += Counter({(name, term):count})

print [(name, count, term) for (name, term), count in dict(c).items()]
#[('apple', 16, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]