广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python中Switch/Case实现的示例代码
  • 234
分享到

python中Switch/Case实现的示例代码

示例代码python 2022-06-04 19:06:18 234人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

学习python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现Switch/Case功能。 使用if…elif…el

学习python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现Switch/Case功能。

使用if…elif…elif…else 实现switch/case

可以使用if…elif…elif..else序列来代替switch/case语句,这是大家最容易想到的办法。但是随着分支的增多和修改的频繁,这种代替方式并不很好调试和维护。

方法一

通过字典实现


def foo(var):
  return {
      'a': 1,
      'b': 2,
      'c': 3,
  }.get(var,'error')  #'error'为默认返回值,可自设置

方法二

通过匿名函数实现


def foo(var,x):
  return {
      'a': lambda x: x+1,
      'b': lambda x: x+2,
      'c': lambda x: x+3, 
  }[var](x)

方法三

通过定义类实现

参考Brian Beck通过类来实现Swich-case


# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
  def __init__(self, value):
    self.value = value
    self.fall = False

  def __iter__(self):
    """Return the match method once, then stop"""
    yield self.match
    raise StopIteration

  def match(self, *args):
    """Indicate whether or not to enter a case suite"""
    if self.fall or not args:
      return True
    elif self.value in args: # changed for v1.5, see below
      self.fall = True
      return True
    else:
      return False


# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
  if case('one'):
    print 1
    break
  if case('two'):
    print 2
    break
  if case('ten'):
    print 10
    break
  if case('eleven'):
    print 11
    break
  if case(): # default, could also just omit condition or 'if True'
    print "something else!"
    # No need to break here, it'll stop anyway

# break is used here to look as much like the real thing as possible, but
# elif is generally just as Good and more concise.

# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain 'pass'
c = 'z'
for case in switch(c):
  if case('a'): pass # only necessary if the rest of the suite is empty
  if case('b'): pass
  # ...
  if case('y'): pass
  if case('z'):
    print "c is lowercase!"
    break
  if case('A'): pass
  # ...
  if case('Z'):
    print "c is uppercase!"
    break
  if case(): # default
    print "I dunno what c was!"

# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic 'case' statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = 'A'
for case in switch(c):
  if case(*string.lowercase): # note the * for unpacking as arguments
    print "c is lowercase!"
    break
  if case(*string.uppercase):
    print "c is uppercase!"
    break
  if case('!', '?', '.'): # nORMal argument passing style also applies
    print "c is a sentence terminator!"
    break
  if case(): # default
    print "I dunno what c was!"

# Since Pierre's suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.
 

查看Python官方:PEP 3103-A Switch/Case Statement

发现其实实现Switch Case需要被判断的变量是可哈希的和可比较的,这与Python倡导的灵活性有冲突。在实现上,优化不好做,可能到最后最差的情况汇编出来跟If Else组是一样的。所以Python没有支持。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: python中Switch/Case实现的示例代码

本文链接: https://www.lsjlt.com/news/16166.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python中Switch/Case实现的示例代码
    学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现。所以不妨自己来实现Switch/Case功能。 使用if…elif…el...
    99+
    2022-06-04
    示例 代码 python
  • 如何在Python中实现真正的switch-case语句
    这篇文章给大家分享的是有关如何在Python中实现真正的switch-case语句的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。在 Python 中实现真正的 switch-case 语句。这是使用字典来模仿 s...
    99+
    2023-06-27
  • vue.js实现开关(switch)组件实例代码
    最近开发组件的时候,自定义开发了开关(switch)组件,现将代码整理如下,方便日后复用。 toggle-switch.vue   <template> <l...
    99+
    2022-11-13
  • Python实现PING命令的示例代码
    目录一、PING简介二、代码实现        三、结果显示一、PING简介 PING(Packet Internet Grope)...
    99+
    2023-01-06
    Python PING命令 Python PING
  • python实现跳表SkipList的示例代码
    跳表 跳表,又叫做跳跃表、跳跃列表,在有序链表的基础上增加了“跳跃”的功能,由William Pugh于1990年发布,设计的初衷是为了取代平衡树(比如红黑树)。 Redis、LevelDB 都是著名的 Key-Va...
    99+
    2022-06-02
    python 跳表SkipList python 跳表
  • python实现自幂数的示例代码
    1、什么是自幂数? 前文介绍过 python 实现水仙花数,其实水仙花数为自幂数的一种,即,3位自幂数。 自幂数是指一个 n 位数,它的每个位上的数字的 n 次幂之和等于它...
    99+
    2022-11-11
  • Python实现计算AUC的示例代码
    目录为什么这样一个指标可以衡量分类效果auc理解AUC计算方法一方法二实现及验证AUC(Area under curve)是机器学习常用的二分类评测手段,直接含义是ROC曲线下的面积...
    99+
    2022-11-11
  • 使用Python实现tail的示例代码
    目录前记1.第一版--从文件尾部读取实时数据2.第二版--实现tail -f3.第三版--优雅的读取输出日志文件前记 tail是一个常用的Linux命令, 它可以打印文件的后面n行数...
    99+
    2023-03-01
    Python实现tail Python tail
  • Python实现PDF转MP3的示例代码
    目录一、PDF转为MP3 二、准备工作三、代码很简单四、变更播音员总结一、PDF转为MP3  我们平常看到很多文件都是PDF格式,网上的各类书籍多为此格式。有时候...
    99+
    2023-05-18
    Python实现PDF转MP3 Python PDF转MP3 Python PDF MP3
  • Python实现连点器的示例代码
    啊,为此我特意准备了两个程序,一个是用来测试的,一个是主程序。来看看吧 直接放连点器代码: # 改进版 import pyautogui as pag from time impor...
    99+
    2022-11-13
  • Python实现屏幕代码雨效果的示例代码
    直接上代码 import pygame import random def main(): # 初始化pygame pygame.init() #...
    99+
    2022-11-13
  • Python实现 MK检验示例代码
    MK检验:时间序列进行检测,并找出突变点,本文参考网上的matlab程序改写为python代码如下: import numpy as np import pandas as pd...
    99+
    2022-11-12
  • Vue+Element switch组件的使用示例代码详解
    代码如下所示: <el-table-column label="商品状态" align="center"> <template slot-sco...
    99+
    2022-11-13
  • python中Tkinter实现分页标签的示例代码
    Tkinter实现UI分页标签显示: Input页,红色部分为当前Frame的位置,下半部分为第一页的子标签;三页标签的显示内容各不相同。实现分页显示的核心组件为Radiobutt...
    99+
    2022-11-12
  • Python实现视频裁剪的示例代码
    目录前言环境依赖代码验证一下前言 本文提供将视频按照自定义尺寸进行裁剪的工具方法,一如既往的实用主义。 环境依赖 ffmpeg环境安装,可以参考文章:windows ffmpeg安装...
    99+
    2022-11-13
  • Python实现边缘提取的示例代码
    目录复习一、边缘提取1、什么是边缘2、什么是边缘提取二、Sobel算子三、Canny边缘检测算法1、算法步骤2、高斯平滑3、非极大值抑制4、双阈值检测四、相关代码复习 (1)梯度: ...
    99+
    2022-11-11
  • python实现图像识别的示例代码
    一、安装库 首先我们需要安装PIL和pytesseract库。 PIL:(Python Imaging Library)是Python平台上的图像处理标准库,功能非常强大。 pyte...
    99+
    2022-11-11
  • Python实现批量翻译的示例代码
    目录截图源码Translator.pyLog.pyUtils.py简单的使用案例Python版本截图 源码 Translator.py #!/usr/bin/python # -*...
    99+
    2022-11-11
  • python实现线性回归的示例代码
    目录1线性回归1.1简单线性回归1.2 多元线性回归1.3 使用sklearn中的线性回归模型1线性回归 1.1简单线性回归 在简单线性回归中,通过调整a和b的参数值,来拟合从x到...
    99+
    2022-11-13
  • Python实现一键抠图的示例代码
    目录需求来源实现方法需求来源 好友 A:橡皮擦,可否提供网页,上传带人像的图片,然后可以直接抠图,最好直接生成 PNG 图片下载。 橡皮擦:每天需要调用多少次? 好友 A:大概 10...
    99+
    2022-11-11
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作