2018年1月27日 星期六

[Python] 常用基本語法

Python基本用法, 快速查詢用, 另外DataCamp有提供相當多資料科學學習資源, 也有Python cheat sheet可供下載, 在此附上連結




DataCamp提供相當多資料科學學習資源, 資料科學所使用的工作過多導致學習上會讓新手陷入困難 , 看小抄就是一個很好的方法用來快速複習語法, 裡面提供Python.Keras.pandas.PySpark.......等小抄, 有興趣可以下載來看看

這裡還有個常見面試題整理寫得很好可以參考
https://zhuanlan.zhihu.com/p/23526961

下面整理一些基本的語法供快速查詢用:


if簡約寫法

(0 if x==“?“ else float(x))

dict寫法

d = { ‘a’:1, ‘b’:2, ‘c’:3 }
d = dict(a=1,b=2,c=3)
d= dict(zip([a,b,c],[1,2,3]))
d = dict([(‘a’,1),(‘b’,2),(‘c’,3)])
for key in d:
     print key
for key in d.keys():
     print key
for value in d.values:
     print value
for key,value in d.items():
     print (key,value)
# 找key值是否存在 or try catch
if dict.has_key('key'):
    print 'find key'
if key in dict:
    print 'find key'
name = some_dict.get('name', 'Bob')#找不到回傳Bob
# dict append data
dict.update({'key':'value','key1':'value1'})
dict['new'] = 'values2'
del dict['new']
kList = list(d.keys())
vList=list(d.values())
list(zip(d.items()))
>>> [(‘a’,1),(‘b’,2),(‘c’,3)]
list(zip(d.values(),d.keys))
>>>[(1:’a’),(2:’b’),(3,’c’)]
## get dict row tuple
field, value = d.items()[0]
d = {‘amy’:(20,50,70), ‘boy’:(50,40,70)}
for x in sorted(d.values())
     print (x, d[x])
def foo(item):
     return item[1][2] #依照tuple第二欄排序
for item sorted(d, key=foo):
     print(item)

#移除重複值
list_fix = {each[‘EmployeeId’] : each for each in list}.values()
li = [0,1,2,3,4,5,6]
for i , x in enumerate(li):
     if x % 2 == 0:
          del li[i]
#defaultdict有預設值的字典
#OrderedDict 具有順序的字典
#frozenset 不可變的集合
(lambda  x,y : x if x > y else y)( 3 , 4 ) #宣告lambda後直接呼叫
li = [(‘a’,1),(‘b’,2)]
sorted( li , key=lambda item: item[0] )
sorted( li , key=lambda item: len(item[0]) )

filter

>>> def fn(x):
...     return x if x > 5 else None
...
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = filter(fn, a)
>>> b
[6, 7, 8, 9]

map

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def fn(x):
...     return x*2
>>> c = map(fn, a)
>>> c
[2, 4, 6, 8, 10, 12, 14, 16, 18]

reduce

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def fn(x, y):
...     return x+y
>>> d = reduce(fn, a)
>>> d
45

decorator

def use_logging(func):

    def wrapper():
        logging.warn("%s is running" % func.__name__)
        return func()
    return wrapper

@use_logging
def foo():
    print("i am foo")

foo()

def use_logging(level):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if level == "warn":
                logging.warn("%s is running" % func.__name__)
            elif level == "info":
                logging.info("%s is running" % func.__name__)
            return func(*args)
        return wrapper

    return decorator

@use_logging(level="warn")
def foo(name='foo'):
    print("i am %s" % name)

foo()

try catch

import sys
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
else:
        i = i + 10
      print("Open file successs.")

我們也可以先建立一個 exception 的 calss ,然後拋出我們定義的異常

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

@property : 類似C#的getter setter

class Egg(object):

    def __init__(self, price):
        self._price = price

    @property
    def price(self):
        return self._price * RATE
    
    @price.setter
    def price(self, value):
        self._price = value

Class (父類別不可宣告的寫法)

import random
from abc import ABCMeta, abstractmethod

class GuessGame(metaclass=ABCMeta):
    @abstractmethod
    def message(self, msg):
        pass

    @abstractmethod
    def guess(self):
        pass     

    def go(self):
        self.message(self.welcome)
        number = int(random.random() * 10)
        while True:
            guess = self.guess();
            if guess > number:
                self.message(self.bigger)
            elif guess < number:
                self.message(self.smaller)
            else:
                break
        self.message(self.correct)

Class 全域變數的寫法

class TestClass():
    g_c = 0
    
    def __init__(self):
        self.g_c2 = 4

    def run(self):
        TestClass.g_c = 1
        self.g_c2 = 5

t = TestClass()
t.run()

t2 = TestClass()

t.g_c, t.g_c2, t2.g_c, t2.g_c2
# >>> (1, 5, 1, 4)

繼承

class ConsoleGame(GuessGame):
    def __init__(self):
        self.welcome = "歡迎"
        self.prompt = "輸入數字:"
        self.correct = "猜中了"
        self.bigger = "你猜的比較大"
        self.smaller = "你猜的比較小"
    
    def message(self, msg):
        print(msg)
    
    def guess(self):
        return int(input(self.prompt))

game = ConsoleGame()
game.go()

如果你真的想要模擬Java中interface的作用,則可以定義一個抽象類別,完全沒有實作的方法即可

import random
from abc import ABCMeta, abstractmethod

class Flyer(metaclass=ABCMeta): # 就像是Java中的interface
    @abstractmethod
    def fly(self):
        pass

class Bird:
    pass
    
class Sparrow(Bird, Flyer):  # 就像Java中繼承Bird類別並實作Flyer介面
    def fly(self):
        print('麻雀飛')

s = Sparrow()
s.fly()

http request

import request

root_url = "http://xxx.xxx.xxx"

def query_data(field='all' , name=None, params=None):

    header={'id':'test'}

    if not params:
        params={}

    if field == 'all':
        return requests.get(root_url + 'all')

    url = '%s/%s/%s'%(root_url,field,name)
    print url
    response =requests.get(url, params=params, headers=headers)

    if not response.status_code == requests.codes.ok:
        raise Exception('fail') + str(response.status_code)

   return response

response = query_data('aaa', 'bbb')
response.json()

Request try except
import request
try:
    r=request.get(url, timeout=3)
    r.raise_for_status()#回應狀態是400~599,print此函數可以取得更多資訊
except requests.exceptions.RequestException as ex1:
    print '404-HTTP請求有錯誤'
except requests.exceptions.HTTPError as ex2:
    print '回應不合法的HTTP內容'
except requests.exceptions.ConnectionError as ex3:
    print '網路orDNS有錯誤'
except requests.exceptions.Timeout as ex4:
    print '408-當HTTP請求超過期限'
except requests.exceptions.TooManyRedirects as ex5:
    print '轉址超過設定的最大值'

沒有留言:

張貼留言