我可以在python中使用rust的匹配吗?

2024-05-23 18:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python3中使用铁锈火柴

而不是if…elif语句。你知道吗

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);
}

Tags: oftheantruenumberismatchrust
1条回答
网友
1楼 · 发布于 2024-05-23 18:26:05

谢谢你的提示,安德里亚·科尔贝里尼。你知道吗

我找到了解决方案,有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")))

相关问题 更多 >