Search code examples
pythonlistsublist

How to divide list into sublists of equal size?


I have a list of crops, I need to divide the list into sublists of 48 items and then plot them in a mosaic, I have been doing it manually. How can I do it automatically?

This is the code I use:

        import matplotlib.pyplot as plt
        from mpl_toolkits.axes_grid1 import ImageGrid
        import numpy as np

        p1 = listf[:48]
        p2 = listf[48:96]
        p3 = listf[96:144]
        p4 = listf[144:192]
        p5 = listf[192:240]
        p6 = listf[240:288]
        p7 = listf[288:336]
        p8 = listf[336:384]
        p9 = listf[384:432]
        p10 = listf[432:480]
        p11 = listf[480:528]
        p12 = listf[528:576]
        p13 = listf[576:624]
        p14 = listf[624:642]


        final = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14]


        for idx, part in enumerate(final):
            nc = 8
            #fig = plt.figure(figsize=(8, (len(part)/6) * 8), dpi=600)
            fig = plt.figure(figsize=(9, 6), dpi=300)
            grid = ImageGrid(fig, 111,  # similar to subplot(111)
                            #nrows_ncols=(int((len(part))/2), nc),  # creates 12x2 grid of axes
                            nrows_ncols=(6, nc),
                            axes_pad=0.2,  # pad between axes in inch.
                            )
            
            for ax, im in zip(grid, part):
                # Iterating over the grid returns the Axes.
                ax.tick_params(labelbottom= False,labeltop = False, labelleft = False,  labelright = False)
                ax.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
            
            fig.suptitle('Predicted vs Real', fontsize=15 )

Solution

  • my_lists = list(zip(*[iter(my_big_list)]*48))
    

    is a common(ish) pattern to do this without numpy or pandas I think

    a more readable version

    split_size = 48
    my_lists = [my_big_list[i:i+split_size] for i in range(0,len(my_big_list),split_size)]