Python - Get percentage of minority class in a list
Question: Suppose I have a list, how can I write an elegant one-liner to calculate the
percentage of the minority class in a list?

For example, for `list1 = [1,1,1,-1,-1]`, the minority class is `-1`. The
percentage of `-1` in the list will be `2/5=0.4`

For another list `list2 = [1,-1,-1,-1,-1]`, the minority class is `1`. The
percentage of `1` in the list will be `1/5=0.2`


Answer: You can use a `Counter`:

    
    
    from collections import Counter
    
    nums = [1,-1,-1,-1,-1]
    # if using Python 2 use float(len(nums))
    print(Counter(nums).most_common()[-1][-1] / len(nums))
    >> 0.2
    

`Counter.most_common()` returns a list of tuples of the form `(element,
count)` ordered from most to least common, so `most_common()[-1][-1]` returns
the element that is the least common.

If there are several minorities, one of them will be chosen arbitrarily for
the calculation. For example, using my code with `nums = [3, 3, -1, 1, 2]`
will also return `0.2`, using either `-1`, `1`or `2` for the calculation.

