import random


def distselect(weight_l):
    """Perform a weighted selection using the weights 
    from the provided list. Return the selected index"""

    if not isinstance(weight_l, list):
        raise Exception("distselect requires a list of values")

    # Create a weight/index vector
    weight_v = []
    total_w = 0
    for i,v in enumerate(weight_l):
        w = int(v)
        total_w += w
        weight_v.append((w, i))
        
    # Order by weight value
    weight_v.sort(key=lambda e:e[0])
    
    rand_v = random.randint(1, total_w)
    
    for we in weight_v:
        rand_v -= we[0]
        
        if rand_v <= 0:
            # Return the selected index
            return we[1]

    # Return the last index
    return weight_v[-1][1]