问题
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