Search code examples
pythonindexingfloating-pointsum

How to add all the same float values in a list then placing these values in a new list


If I have a list (listA) of floats with repeating values, how would I add the same repeating values together and put them in a new list (listB)?

For example:

listA = [1.356, 7.663, 12.466, 1.356, 7.663, 12.466, 1.356, 7.663, 12.466]

The values 1.356, 7.663, 12.466 are repeated 3x. I would like to add the same values together and put them in a new list:

listB = [4.068, 22.989, 37.398]

The first value is the sum of all 1.356, the 2nd value sum of 7.663 etc.


Solution

  • This can be broken down in two steps:

    1. count how often each number occurs
    2. multiply each number by how often it occurs and add the result to a list

    The first step is what collections.Counter exists for.

    >>> from collections import Counter
    >>> c = Counter(listA)
    >>> c
    Counter({1.356: 3, 7.663: 3, 12.466: 3})
    

    For the second step, iterate over the (value, count) pairs in Counter object by using its items method (inherited from dict):

    >>> listB = []
    >>> for value, count in c.items():
    ...     listB.append(value * count)
    ...
    >>> listB
    [4.0680000000000005, 22.989, 37.397999999999996]
    

    Or in short:

    listB = [value * count for value, count in Counter(listA).items()]