Search code examples
pythonlisttuplescategorization

Categorization the list of tuples in Python


help me please I'm trying to find out the fastest and logical way to categorize tuple list by values of the first tuple element. for example I have a list with tuples like

a = [(378, 123), (100, 12), (112, 23), (145, 14), (165, 34), (178, 45), (227, 32), (234, 12), (356, 15)] # and more and more

How I can dynamically categorize it into a groups like

100to150 = [(100, 12), (112, 23), (145, 14)]
150to200 = [(165, 34), (178, 45)]
200to250 = [(227, 32), (234, 12)]
350to400 = [(378, 123), (356, 15)]

In this way I used step 50, but I want to have an ability to change it of course. It doesn't matter what will be in output, maybe list in list for example [[(100, 112), (124, 145)], [(165, 12), (178, 12)], [(234, 14)], [(356, 65)]] (random data) or maybe a list with a tuple, it doesn't matter. I just want to have an ability to get the length of the category and print category out. Thank you much.


Solution

  • You can try something like this. This will give of course give you back a categorized dictionary though, not separate variables.

    a = [(378, 123), (100, 12), (112, 23), (145, 14), (165, 34), (178, 45), (227, 32), (234, 12), (356, 15)] # and more and more
    
    def categorize(array, step=50):
            d = dict()
            for e in array:
                    from_n = e[0]//step*step
                    s = f'{from_n}to{from_n+step}'
                    if s not in d:
                            d[s] = []
                    d[s].append(e)
            return d
    
    print(categorize(a))
    

    Output:

    {'350to400': [(378, 123), (356, 15)], '100to150': [(100, 12), (112, 23), (145, 14)], '150to200': [(165, 34), (178, 45)], '200to250': [(227, 32), (234, 12)]}