python & dict & switch


python & dict & switch

python 中是沒用switch語句的,這應該是體現python大道至簡的思想,python中一般多用字典來代替switch來實現。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 22:12:43 2019

@author: xgqfrms-mbp
"""

#coding: utf-8
from __future__ import division
  
def jia(x,y):
    print(x+y);
  
def jian(x,y):
    print(x-y);
  
def cheng(x,y):
    print(x*y);
  
def chu(x,y):
    print(x/y);
  
operator = {'+':jia,'-':jian,'*':cheng,'/':chu};
  
def f(x,o,y):
    operator.get(o)(x,y);
  
f(3,'+',2);

object === dict

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 22:12:43 2019

@author: xgqfrms-mbp
"""

#coding: utf-8
from __future__ import division
  
def jia(x,y):
    print(x+y);
  
def jian(x,y):
    print(x-y);
  
def cheng(x,y):
    print(x*y);
  
def chu(x,y):
    print(x/y);
  
operator = { '+': jia, '-': jian, '*': cheng, '/': chu, };

# operator = {
#   '+ : jia,
#   '-' : jian,
#   '*' : cheng,
#   '/' : chu
# };
# SyntaxError: EOL while scanning string literal

def f(x,o,y):
    operator.get(o)(x,y);

f(3,'+',2);
# 5

refs

https://docs.python.org/3/tutorial/index.html

https://code.visualstudio.com/docs/languages/python

https://pypi.org/search/?c=Operating+System+%3A%3A+MacOS


Flag Counter

&copyxgqfrms 2012-2020

www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM