包含python之switch語句的詞條

本文目錄一覽:

python中有switch語句嗎

python官網的回答(地址:):

You can do this easily enough with a sequence of if… elif… elif… else.

意思就是:python語法講究簡單明了,if else完全可以很簡單的實現switch的所有功能,沒必要用switch。

為什麼Python中沒有Switch/Case語句

因為作為一門解釋型語言,switch/case是沒有存在必要的,if/elif/else就可以實現的功能,為什麼要再提供重複的?

if else的得一個if一個if的判斷過去,如果匹配的是最後一個條件,前面所有if都得判斷一遍的。

看過彙編就知道,C語言的switch/case,在case值連續的時候,是可以根據case值直接計算該跳轉的地址的。

Python里怎麼實現switch case

學習Python過程中,發現沒有switch-case,過去寫C習慣用Switch/Case語句,官方文檔說通過if-elif實現。所以不妨自己來實現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沒有支持。

如何理解 python中的switch

方法/步驟

1

我們以加減和一個隨意名字的函數來解析switch的用法,說白了也是很簡答嗎的。首先添加一個add的方法。

2

再添加一個相減的方法,同時加了print方便debug程序。

3

之後為了作對比,隨便寫了一個abc的方法。

4

建立一個字典,用‘+’,‘-’,‘abc’分別作為key,對應相映的方法。

5

之後再加兩個方法,通過對於參數的調整,用字典的get‘key’方法獲取函數,並且傳入參數。

6

試着用(1,‘+’,5) 來實現1+5。

7

用(6,‘-’,2) 來實現6-2,調用的都是同一個方法,參數不同,通過字典key獲取到的函數也不同,這就是我所理解的switch的用法。

8

最後,隨便試一下,用‘abc’也可以,哈哈。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/280742.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-21 13:04
下一篇 2024-12-21 13:04

相關推薦

  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29

發表回復

登錄後才能評論