can i use rust's match in python? [closed]

本秂侑毒 提交于 2021-02-08 12:13:46

问题


i want to use rust match in python3,

instead of if...elif statement.

https://doc.rust-lang.org/rust-by-example/flow_control/match.html

fn main() {
    let number = 13;
    // TODO ^ Try different values for `number`

    println!("Tell me about {}", number);
    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // Match an inclusive range
        13...19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
    }

    let boolean = true;
    // Match is an expression too
    let binary = match boolean {
        // The arms of a match must cover all the possible values
        false => 0,
        true => 1,
        // TODO ^ Try commenting out one of these arms
    };

    println!("{} -> {}", boolean, binary);
}

回答1:


Thanks for the hint, Andrea Corbellini.

i found that solution, there is pampy

from pampy import match, _

def func(x):
    return match(x,
          1, "One!",
          # 2 | 3 | 5 | 7 | 11, "This is a prime",     # not work
          # 2 or 3 or 5 or 7 or 11, "This is a prime", # not work
          2, "This is a prime",
          _, "Ain't special"
    )

if __name__ == '__main__':
    print("1: {}".format(func(1)))
    print("2: {}".format(func(2)))
    print("3: {}".format(func(3)))
    print("5: {}".format(func(5)))
    print("7: {}".format(func(7)))
    print("nothing: {}".format(func("nothing")))

--

EDIT: Now (2020/06), there is official draft for match PEP 622



来源:https://stackoverflow.com/questions/59098889/can-i-use-rusts-match-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!