介绍

  • MicroPython 不支持

match case

  1. flag = False
  2. match (100, 200):
  3. case (100, 300): # Mismatch: 200 != 300
  4. print('Case 1')
  5. case (100, 200) if flag: # Successful match, but guard fails
  6. print('Case 2')
  7. case (100, y): # Matches and binds y to 200
  8. print(f'Case 3, y: {y}')
  9. case _: # Pattern not attempted
  10. print('Case 4, I match anything!')

方式二

  1. def switch_case(value):
  2. switcher = {
  3. 0: "zero",
  4. 1: "one",
  5. 2: "two",
  6. }
  7. return switcher.get(value, 'wrong value')
  • 使用匿名函数方式实现:
  1. def foo(var,x):
  2. return {
  3. 'a': lambda x: x+1,
  4. 'b': lambda x: x+2,
  5. 'c': lambda x: x+3,
  6. }[var](x)