Search code examples
pythonfrequency-analysis

How to count frequency of multiple combination of value in Python


I'm new here and a newbie in Python. I'd like to ask a question about calculating frequency for multiple combination of variables in Python.

I have a list of a lists that looks like this for example:

[[A,A,A],[A,B,C],[A,A,A],[A,B,B],[A,B,C]]

And I want python to count the frequency for all combination in that list, and the result will look like this:

[[A,A,A,2],[A,B,C,2],[A,B,B,1]]

Is there any possible way in Python to do that, or is there any python module that supports something similar to that? I've found a function in Arcpy module that I think similar to what I want to do here but I don't own any ArcGIS license or software so I can't get access to use that function.


Solution

  • Without using additional libraries:

    listOfItems = [['A','A','A'],['A','B','C'],['A','A','A'],['A','B','B'],['A','B','C']]
    setOfItems = []
    newListOfItems = []
    for item in listOfItems:
        if item in setOfItems:
            continue
        setOfItems.append(item)
        temp = list(item)
        occurence = listOfItems.count(item)
        temp.append(occurence)
        newListOfItems.append(temp)
    
    print newListOfItems
    

    Result is:

       >>> print newListOfItems
       [['A', 'A', 'A', 2], ['A', 'B', 'C', 2], ['A', 'B', 'B', 1]]