Search code examples
pythonlistiterationgroupinglist-comprehension

Pythonic way to group values from a list based on values from another list


I have 2 lists:

List_A = [1, 25, 40]
List_B = [2, 19, 23, 26, 30, 32, 34, 36]

I want to generate a list of lists such that I group values in list B by determining if they are in between values in list A. So in this example, list B would be grouped into:

[[2,19,23], [26,30,32,34,36]]

Is there any clean way in python to achieve this without multiple nested for loops?

Tried a messy double nested loop structure, was not pleased with how clunky it was (due to lack of readability).


Solution

  • This is the simplest way I can think of to code it.

    result = []
    for start, end in zip(List_A, List_A[1:]):
        result.append([i for i in List_B if start <= i < end])
    

    It's O(NxM), so not very efficient for large lists.

    You could make it more efficient by sorting List_B (I assume List_A is already sorted) and stepping through both of them together, but it will be more complicated.