【问题标题】:Is there a way to match inequalities in Python ≥ 3.10?有没有办法匹配 Python ≥ 3.10 中的不等式?
【发布时间】:2021-12-11 01:45:06
【问题描述】:

Python 3.10 中新的结构模式匹配功能是一个非常受欢迎的功能。有没有办法使用这个语句来匹配不等式?原型示例:

match a:
    case < 42:
        print('Less')
    case == 42:
        print('The answer')
    case > 42:
        print('Greater')

【问题讨论】:

  • 我个人会在匹配(不)等式而不是结构模式时使用简单的if elif else 语句。

标签: python pattern-matching python-3.10


【解决方案1】:

你可以使用guards:

match a:
   case _ if a < 42:
      print('Less')
   case _ if a == 42:
     print('The answer')
   case _ if a > 42:
     print('Greater')

另一种选择,没有保护,使用纯模式匹配:

match [a < 42, a == 42]:
   case [True, False]:
      print('Less')
   case [_, True]:
      print('The answer')
   case [False, False]:
      print('Greater')

【讨论】:

  • 使用条件检查看起来很简洁。不错!
  • 两种解决方案都很棒!谢谢
  • 让我头疼。
猜你喜欢
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多