[Python] How to use match case for list with a specific element in an arbitrary index?

Discussão em 'Python' iniciado por Stack, Novembro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I am making a simple math interpreter in python. The program converts the math string to a list of numbers and operations which is then evaluated using match case.

    I want to do something like this:

    c = ['12', '-', '24', '/', '6', '+', '7']
    match c:
    case [*before_div, '/', *after_div]:
    ...


    The other option would be matching against the general case and trying to find this character to split the list at its index. Like this:

    match c:
    case [*_]:
    try:
    i = c.index("/")
    before_div, after_div = c[:i], c[i+1:]
    ...
    except ValueError:
    pass


    But this could end the matching without successfully processing anything.

    Continue reading...

Compartilhe esta Página