<small id='6PLuv'></small><noframes id='6PLuv'>

    <i id='6PLuv'><tr id='6PLuv'><dt id='6PLuv'><q id='6PLuv'><span id='6PLuv'><b id='6PLuv'><form id='6PLuv'><ins id='6PLuv'></ins><ul id='6PLuv'></ul><sub id='6PLuv'></sub></form><legend id='6PLuv'></legend><bdo id='6PLuv'><pre id='6PLuv'><center id='6PLuv'></center></pre></bdo></b><th id='6PLuv'></th></span></q></dt></tr></i><div id='6PLuv'><tfoot id='6PLuv'></tfoot><dl id='6PLuv'><fieldset id='6PLuv'></fieldset></dl></div>

    1. <tfoot id='6PLuv'></tfoot>

        <bdo id='6PLuv'></bdo><ul id='6PLuv'></ul>
    2. <legend id='6PLuv'><style id='6PLuv'><dir id='6PLuv'><q id='6PLuv'></q></dir></style></legend>

        如何创建一个案例为间隔的开关案例?

        How to create a switch case with the cases being intervals?(如何创建一个案例为间隔的开关案例?)
          <tbody id='wgQt8'></tbody>

        <tfoot id='wgQt8'></tfoot>

      1. <small id='wgQt8'></small><noframes id='wgQt8'>

            <legend id='wgQt8'><style id='wgQt8'><dir id='wgQt8'><q id='wgQt8'></q></dir></style></legend>
            <i id='wgQt8'><tr id='wgQt8'><dt id='wgQt8'><q id='wgQt8'><span id='wgQt8'><b id='wgQt8'><form id='wgQt8'><ins id='wgQt8'></ins><ul id='wgQt8'></ul><sub id='wgQt8'></sub></form><legend id='wgQt8'></legend><bdo id='wgQt8'><pre id='wgQt8'><center id='wgQt8'></center></pre></bdo></b><th id='wgQt8'></th></span></q></dt></tr></i><div id='wgQt8'><tfoot id='wgQt8'></tfoot><dl id='wgQt8'><fieldset id='wgQt8'></fieldset></dl></div>
              • <bdo id='wgQt8'></bdo><ul id='wgQt8'></ul>

                  本文介绍了如何创建一个案例为间隔的开关案例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我想创建一个开关/案例,其中案例可以有间隔作为条件,例如:

                  I'd like to create a switch/case where the cases can have intervals as condition, like:

                  switch = {
                      1..<21: do one stuff,
                      21...31: do another
                  }
                  

                  我怎样才能达到这个结果?

                  How can I achieve this result?

                  推荐答案

                  在 Python 3.10 中引入了显式 switch 语句 - 匹配.虽然它不支持直接遏制检查,但我们必须利用 守卫功能:

                  In Python 3.10 an explicit switch statement was introduced - match. Although it doesn't support direct containment checking, so we'll have to exploit the guard feature:

                  number = int(input("num: "))
                  
                  match number:
                      case num if 1 <= num <  21:
                          # do stuff
                      case num if 21 <= num < 31:
                          # do other stuff
                      case _:
                          # do default
                  

                  但在这一点上,它引出了一个问题,为什么不直接使用 if/elif/else 结构......取决于个人喜好.

                  But at this point it begs the question why not just use an if/elif/else structure... Up to personal taste.

                  对于早期版本,您似乎已经尝试过,在 Python 中实现 switch 结构的明显方法是使用字典.

                  For earlier versions, as it looks like you already tried, the obvious way of implementing a switch structure in Python is using a dictionary.

                  为了支持intervals,你可以实现自己的dict类:

                  In order to support intervals, you could implement your own dict class:

                  class Switch(dict):
                      def __getitem__(self, item):
                          for key in self.keys():                 # iterate over the intervals
                              if item in key:                     # if the argument is in that interval
                                  return super().__getitem__(key) # return its associated value
                          raise KeyError(item)                    # if not in any interval, raise KeyError
                  

                  现在您可以使用 ranges 作为键:

                  And now you can use ranges as keys:

                  switch = Switch({
                      range(1, 21): 'a',
                      range(21, 31): 'b'
                  })
                  

                  还有几个例子:

                  >>> print(switch[4])
                  a
                  
                  >>> print(switch[21])
                  b
                  
                  >>> print(switch[0])
                  KeyError: 0
                  


                  另一种选择是解包范围并单独保存范围的每个数字.比如:


                  Another option is to unpack the ranges and save each number of the range individually. Something like:

                  cases = {range(1, 21): 'a',
                           range(21, 31): 'b'
                          }
                  
                  switch = {num: value for rng, value in cases.items() for num in rng}
                  

                  其余的工作相同.

                  这两个选项的区别是第一个节省内存,但失去了dicts的时间效率(当你检查所有键时),而第二个将保持dict的O(1) 以占用更多内存为代价的查找(所有范围的内容加在一起).

                  The difference between the two options is that the first saves memory, but loses the time efficiency of dicts (as you check all the keys), while the second one will maintain the dict's O(1) look-up at the cost of taking more memory (the contents of all ranges together).

                  根据您的应用程序,您可以在它们之间进行选择,一般来说:

                  According to your application you can choose between them, as a general rule:

                  • 很少的远距离 - 第一个选项
                  • 许多短距离 - 第二种选择
                  • 介于两者之间 - 为您的案例找到最佳解决方案

                  这篇关于如何创建一个案例为间隔的开关案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Initialize Multiple Numpy Arrays (Multiple Assignment) - Like MATLAB deal()(初始化多个 Numpy 数组(多重赋值) - 像 MATLAB deal())
                  How to extend Python class init(如何扩展 Python 类初始化)
                  What#39;s the difference between dict() and {}?(dict() 和 {} 有什么区别?)
                  What is a wrapper_descriptor, and why is Foo.__init__() one in this case?(什么是 wrapper_descriptor,为什么 Foo.__init__() 在这种情况下是其中之一?)
                  Initialize list with same bool value(使用相同的布尔值初始化列表)
                  setattr with kwargs, pythonic or not?(setattr 与 kwargs,pythonic 与否?)
                      <tbody id='aygFu'></tbody>
                    <tfoot id='aygFu'></tfoot>
                    <i id='aygFu'><tr id='aygFu'><dt id='aygFu'><q id='aygFu'><span id='aygFu'><b id='aygFu'><form id='aygFu'><ins id='aygFu'></ins><ul id='aygFu'></ul><sub id='aygFu'></sub></form><legend id='aygFu'></legend><bdo id='aygFu'><pre id='aygFu'><center id='aygFu'></center></pre></bdo></b><th id='aygFu'></th></span></q></dt></tr></i><div id='aygFu'><tfoot id='aygFu'></tfoot><dl id='aygFu'><fieldset id='aygFu'></fieldset></dl></div>

                    <small id='aygFu'></small><noframes id='aygFu'>

                    • <bdo id='aygFu'></bdo><ul id='aygFu'></ul>

                          <legend id='aygFu'><style id='aygFu'><dir id='aygFu'><q id='aygFu'></q></dir></style></legend>