Summing values in nested list when item changes

后端 未结 5 1170
眼角桃花
眼角桃花 2021-01-23 07:45

I have some problem which has stumped my beginner-knowledge of python and I hope someone out there can point me in the correct direction.

I generated a nested list, each

5条回答
  •  清歌不尽
    2021-01-23 08:09

    Problem's like this calls for itertools.groupby. Particularly groupby, groups consecutive values with same keys, where keys can be specified by user. Nevertheless, in this case, key is trivial enough as indexing a particular element of a list, so that should be a reason enough to use operator.itemgetter. Finally, you can wrap up either as a functional (using map/imap) or as a generator expression based on your taste and choice.

    >>> from itertools import groupby, imap
    >>> from operator import itemgetter
    >>> lst=[[1, 0],[1, 2],[2, 9],[3, 0],[3, 8],[3, 1]]
    >>> [[k, sum(imap(itemgetter(1), v))]
         for k, v in groupby(lst,key = itemgetter(0))]
    [[1, 2], [2, 9], [3, 9]]
    

提交回复
热议问题