[Python] How can I check that a list has one and only one truthy value?

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

  1. Stack

    Stack Membro Participativo

    In python, I have a list that should have one and only one truthy value (that is, bool(value) is True). Is there a clever way to check for this? Right now, I am just iterating across the list and manually checking:

    def only1(l)
    true_found = False
    for v in l:
    if v and not true_found:
    true_found=True
    elif v and true_found:
    return False #"Too Many Trues"
    return true_found


    This seems inelegant and not very pythonic. Is there a cleverer way to do this?

    Continue reading...

Compartilhe esta Página