[Python] Eliminating list elements having string from another list

Discussão em 'Python' iniciado por Stack, Março 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to a get a subset of elements of L1, which do not match with any element of another list

    >>> L1 = ["apple", "banana", "cherry", "date"]
    >>> L2 = ["bananaana", "datedate"]
    >>>


    For instance, from these two lists, I want to create a list ['apple', 'cherry']

    >>> [x for x in L1 for y in L2 if x in y]
    ['banana', 'date']
    >>>


    The above nested list comprehension helps to get element which matches, but not other way

    >>> [x for x in L1 for y in L2 if x not in y]
    ['apple', 'apple', 'banana', 'cherry', 'cherry', 'date']
    >>>

    ^^^^^^^^ I was expecting here ['apple', 'cherry']

    Continue reading...

Compartilhe esta Página