[Python] Creating lists of unique elements from lists of list

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    Similar questions have been asked but I am unable to understand the answers. Hence I need some help here...

    I have a list of lists that have sorted numbers. I need to modify this list to include lists that have consecutive numbers.

    eg:

    [[1,2],[3,4],[5,6]] ---> [[1,2],[3,4],[5,6]]

    [[1,2],[2,3],[5,6]] ---> [[1,2,3],[5,6]]

    [[1,2],[2,3],[3,4]] ---> [[1,2,3,4]]

    I tried my code but it does not work the way I intend it to

    lx = [[1,2],[2,3],[3,4]]

    for ii in range(len(lx)-1):
    if len(set(lx[ii]) & set(lx[ii+1])):
    lx[ii] = np.unique(lx[ii]+lx[ii+1])

    lx


    The output of this is: [array([1, 2, 3]), array([2, 3, 4]), [3, 4]]

    How do I get this to work?

    Thank you R

    Continue reading...

Compartilhe esta Página