在列表中添加已排序的元素

时间:2014-04-24 23:54:20

标签: python sortedlist

我有一个列表[" Roll_Number","主题中的标记"]:

list_1=[(1,22),(1,22),(2,29),(2,16),(3,56),(4,32),(4,12)]

我在python中尝试了这个代码,以获得每个roll_no的所有主题的总和:

 sub_sum = [0] * 4 #Roll No :4
 if i in range(0,len(list1)):
 if k in range(0,5):
    if (list1[i][0]==k):
       sub_sum[k] = list1[i][1] + sub_sum[k]
       i=i+1
    else:
        k=k+1
        break

获得无限循环。 预期成果:1:44 , 2:45, 3:56 , 4:44 提前谢谢。

5 个答案:

答案 0 :(得分:3)

您可以按照以下方式执行此操作:

from collections import defaultdict

a = [(1,22),(1,22),(2,29),(2,16),(3,56),(4,32),(4,12)]

b = defaultdict(lambda: 0)
for i,j in a:
    b[i] += j

>>> print b
{1:44, 2:45, 3:56, 4:44}

DEMO

答案 1 :(得分:1)

由于您的列表已按第一个元素排序,因此您可以使用itertools.groupby作为相对简单的单行解决方案:

>>> from itertools import groupby as gb
>>> from operator import itemgetter
>>> 
>>> l = [(1,22),(1,22),(2,29),(2,16),(3,56),(4,32),(4,12)]
>>> 
>>> {a: sum(t[1] for t in b) for a,b in gb(l, itemgetter(0))}
{1: 44, 2: 45, 3: 56, 4: 44}

答案 2 :(得分:1)

使用defaultdict

>>> list_1=[(1,22),(1,22),(2,29),(2,16),(3,56),(4,32),(4,12)]
>>> from collections import defaultdict
>>> res = defaultdict(int)
>>> for key, val in list_1:
...   res[key] += val
... 
>>> print res
defaultdict(<type 'int'>, {1: 44, 2: 45, 3: 56, 4: 44})
>>> print dict(res)
{1: 44, 2: 45, 3: 56, 4: 44}

答案 3 :(得分:1)

您还可以使用groupby

中的itertools
>>> from itertools import groupby
>>> from operator import itemgetter
>>> result = [(k, sum(r[1] for r in rows)) for k, rows in groupby(list_1, key=itemgetter(0))]
>>> result
[(1, 44), (2, 45), (3, 56), (4, 44)]

答案 4 :(得分:0)

不是最直观的

from collections import Counter
from itertools import chain, repeat
Counter(chain.from_iterable(repeat(x, y) for x, y in list_1))
Counter({3: 56, 2: 45, 1: 44, 4: 44})