python開發學習-day03(set集合、collection系列 、深淺拷貝、函數)

s12-20160116-day03html

pytho自動化開發 day03

Date:2016.01.16

@南非波波

課程大綱:python

day2 http://www.cnblogs.com/wupeiqi/articles/5115190.htmlgit

day3 http://www.cnblogs.com/wupeiqi/articles/5133343.htmlgithub

1、set集合

博客連接:http://www.cnblogs.com/songqingbo/p/5128066.htmlweb

優勢:訪問速度快;
     自帶一套解決元素重複的解決方案

測試程序算法

old_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
}
new_dict = {
    "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 },
}

獲取三個列表:
    1. 須要更新的列表 update_list
    2. 須要刪除的列表 del_list
    3. 須要增長的列表 add_list

代碼實現:
    #!/usr/local/env python3
    '''
    Author:@南非波波
    Blog:http://www.cnblogs.com/songqingbo/
    E-mail:qingbo.song@gmail.com
    '''

    old_dict = {
        "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
    }
    new_dict = {
        "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },
        "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },
        "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 },
    }

    #設置set
    old_set = set(old_dict.keys())
    new_set = set(new_dict.keys())

    #更新的set
    update_set = new_set.intersection(old_dict)
    delate_set = old_set.difference(update_set)
    add_set = new_set.difference(update_set)

    update_list = []
    del_list = []
    add_list = []
    # print(update_set)
    # print(delate_set)
    # print(add_set)
    for i in update_set:
        update_list.append({i:new_dict[i]})
        print('須要更新的列表:%s' % update_list)

    for i in delate_set:
        del_list.append({i:old_dict[i]})
        print("須要刪除的列表:%s" % del_list)

    for i in add_set:
        add_list.append({i:new_dict[i]})
        print("須要增長的列表:%s" % add_list)

2、collection系列

博客連接:http://www.cnblogs.com/songqingbo/p/5137785.htmljson

不經常使用功能,須要進行模塊功能導入:
    import collection

Counter

經常使用方法測試:canvas

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import collections

obj = collections.Counter('sjndsjkdsdmslaladsldsldms')

print("輸出字符出現的次數字典:")
for k,v in obj.items():
    print("{%s:%s}" % (k,v))

print("輸出每個字符:") #遍歷獲取原始字符元素
for k in obj.elements():
    print(k)

print("輸出前四個出現次數最多的字符:")
for k in obj.most_common(4):
    print(k)


輸出結果:
    輸出字符出現的次數字典:
    {s:7}
    {l:4}
    {m:2}
    {d:6}
    {k:1}
    {n:1}
    {j:2}
    {a:2}
    輸出每個字符:
    s
    s
    s
    s
    s
    s
    s
    l
    l
    l
    l
    m
    m
    d
    d
    d
    d
    d
    d
    k
    n
    j
    j
    a
    a
    輸出前四個出現次數最多的字符:
    ('s', 7)
    ('d', 6)
    ('l', 4)
    ('m', 2)

_missing_segmentfault

    功能:對於不存在的元素,返回計數器爲0
    import collections
    c = collections.Counter('adjsdkskdjksjaksklklakl')
    c.__missing__(5)
    返回結果:0

most_commonapi

  功能:獲取出現次數的前幾個字母排名
    import collections
    c = collections.Counter('adjsdkskdjksjaksklklakl')
    c.most_common(3)
    [('k', 7), ('s', 4), ('a', 3)]
    c.most_common(8)
    [('k', 7), ('s', 4), ('a', 3), ('j', 3), ('l', 3), ('d', 3)]

elements

    功能:計數器中的全部元素,而且按照ascii碼進行了排序
        返回一個迭代器。元素被重複了多少次,在該迭代器中就包含多少個該元素。全部元素按照字母序排序,個數小於1的元素不被包含。
    import collections
    c = collections.Counter('adjsdkskdjksjaksklklakl')
    sorted(c.elements())
    返回結果:['a', 'a', 'a', 'd', 'd', 'd', 'j', 'j', 'j', 'k', 'k', 'k', 'k', 'k', 'k', 'k','l', 'l', 'l', 's', 's', 's', 's']

計數值的訪問與缺失的鍵

    功能:默認將計數器中全部的字符認爲一個鍵,而後統計鍵出現的次數,即鍵值。若是鍵不存在則返回0.
    import collections
    c = collections.Counter('adjsdkskdjksjaksklklakl')
    >>> c['a']
    3
    >>> c['b']
    0
    >>> c['l']
    3

update && subtract

    功能:都是更新計數器,update是增長,subtract是減小
    import collections
    >>> c = collections.Counter('which')
    >>> c['h']  #這裏的h出現2次
    2
    >>> c.update('with')
    >>> c
    Counter({'h': 3, 'i': 2, 'w': 2, 't': 1, 'c': 1})
    >>> c['h'] #這裏則完成了update操做,h出現了3次
    3

    >>> c.subtract('with') 
    >>> c
    Counter({'h': 2, 'c': 1, 'i': 1, 'w': 1, 't': 0})
    >>> c['h'] #這裏完成subtract操做以後,h出現的次數又恢復到2次
    2

del

    功能:刪除鍵
    import collections
    >>> c = collections.Counter('which')
    >>> c['h']  #這裏的h出現2次
    2
    >>> del c['h']
    >>> c
    Counter({'c': 1, 'i': 1, 'w': 1, 't': 0})
    >>> c['h']  #del操做刪除了鍵'h'
    0

copy

    功能:淺拷貝
    import collections
    >>> c = collections.Counter('which')
    >>> d = c.copy()
    >>> d
    Counter({'h': 2, 'c': 1, 'i': 1, 'w': 1})
    >>> id(c)
    7150792
    >>> id(d)
    6511976

算術和集合操做

功能:+、-、&、|操做也能夠用於Counter。其中&和|操做分別返回兩個Counter對象各元素的最小值和最大值。須要注意的是,獲得的Counter對象將刪除小於1的元素。

經常使用操做

說明:Counter繼承dict的全部方法,經常使用的操做列在下面,僅供參考

有序字典orderedDict

  有序字典繼承字典的一切屬性,只是在順序上是有序的。
  d = collections.OrderedDict({'name':'swht','age':18})
  print(d)
  返回結果:OrderedDict([('name', 'swht'), ('age', 18)])
  print(type(d))
  返回結果:<class 'collections.OrderedDict'>

movetoend

    功能:將指定的鍵值對從開頭移動到末尾。
    d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
    d.move_to_end('name')
    print(d)
    返回結果:OrderedDict([('age', 18), ('address', 'shandong'), ('name', 'swht')])

pop

    功能:移除字典鍵值,並返回刪除鍵值的values
    d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
    d.pop('address')
    print(d)
    返回結果:OrderedDict([('age', 18), ('name', 'swht')])

clear

    功能:清空有序字典的值
    d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
    d.clear()
    print(d)
    返回結果:OrderedDict()

keys,values,items

    功能:繼承字典的屬性,獲取字典的全部鍵和全部值
    d = collections.OrderedDict({'name':'swht','age':18,'address':'shandong',})
    l1 = d.keys()
    l2 = d.values()
    l3 = d.items()
    print(l1,l2,l3)
    返回結果:odict_keys(['address', 'age', 'name']) odict_values(['shandong', 18, 'swht']) odict_items([('age', 18), ('name', 'swht'), ('address', 'shandong')])

默認字典defaultdict

defaultdict是對字典的類型的補充,他默認給字典的值設置了一個類型。建立一個默認字典,value值類型爲列表.
dic = collections.defaultdict(list)

可命名元組nametuple

沒有現成的類,用戶須要自行建立相應的類

測試代碼

#!/usr/local/env python3
'''
Author:@南非波波
Blog:http://www.cnblogs.com/songqingbo/
E-mail:qingbo.song@gmail.com
'''
import collections
MytupleClass = collections.namedtuple("MytupleClass",['x','y','z'])
obj = MytupleClass(11,22,33)
print(obj.x,obj.y,obj.z)
返回結果:11 22 33
總結:至關於在元組的基礎上增長一個key,使其成爲一個類字典的樣子

隊列

雙向隊列

下面兩種方法均可以建立雙向列表,雖然在最初的引用的類不一樣,但最後建立的類型 都是collections.deque
#建立雙向隊列
import collections
d = collections.deque()
返回結果:<class 'collections.deque'>

#but這樣建立雙向隊列呢
import queue
p = queue.deque()
print(type(p))
#<class 'collections.deque'>

單向隊列

#建立單向隊列
import queue
q = queue.Queue()
print(type(q))
#<class 'queue.Queue'>

3、深淺拷貝

博客連接:http://www.cnblogs.com/songqingbo/p/5139015.html

#對於 數字 和 字符串 而言,賦值、淺拷貝和深拷貝無心義,由於其永遠指向同一個內存地址
    import copy
    a1 = 22255
    a2 = 22255
    print(id(a1),id(a2)) #3428240 3428240

#對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,其內存地址的變化是不一樣的。

    import copy
    #字典
    n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
    ##賦值
    n2 = n1
    print(n1,n2) #{'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]} {'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]}
    print(id(n1),id(n2))  #6674440 6674440 #內存地址同樣
    ##淺拷貝
    n3 = copy.copy(n1)
    print(n1,n3) #{'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]} {'k1': 'wu', 'k2': 123, 'k3': ['alex', 456]}
    print(id(n1),id(n3)) #6936584 12067848  #淺拷貝第一級,內存地址相同
    print(id(n1['k3']),id(n3['k3'])) #18741768 18741768
    ##深拷貝
    n4 = copy.deepcopy(n1)
    print(n1,n4) #{'k3': ['alex', 456], 'k2': 123, 'k1': 'wu'} {'k3': ['alex', 456], 'k1': 'wu', 'k2': 123}
    print(id(n1),id(n4)) #6805512 11736904
    print(id(n1['k3']),id(n4['k3'])) #7601032 7599496 #深拷貝第二級,內存地址也不相同

    #列表
    n1 = [1,2,3,4,5,[6,7],]
    ##賦值
    n2 = n1
    print(n1,n2) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n2)) #18609928 18609928
    print(id(n1[5]),id(n2[5])) #18609544 18609544
    ##淺拷貝
    n3 = copy.copy(n1)
    print(n1,n3) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n3)) #18609928 18232904
    print(id(n1[5]),id(n3[5])) #18609544 18609544
    ##深拷貝
    n4 = copy.deepcopy(n1)
    print(n1,n4) #[1, 2, 3, 4, 5, [6, 7]] [1, 2, 3, 4, 5, [6, 7]]
    print(id(n1),id(n4)) #18609928 18611848
    print(id(n1[5]),id(n4[5])) #18609544 18611912


    #元組
    一個小插曲:
        import copy
        n1 = (1,2,3,4,5,(6,7,),)
        #賦值
        n2 = n1
        print('n1:',n1,'n2:',n2) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n2)) #10416584 10416584
        print(id(n1[5]),id(n2[5])) #18415304 18415304
        print(type(n1),type(2)) #<class 'tuple'> <class 'int'>
        #淺拷貝
        n3 = copy.copy(n1)
        print('n1:',n1,'n3:',n3) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n3)) #10416584 10416584
        print(id(n1[5]),id(n3[5])) #18415304 18415304
        print(type(n1),type(3)) #<class 'tuple'> <class 'int'>
        #深拷貝
        n4 = copy.deepcopy(n1)
        print('n1:',n1,'n4:',n4) #n1: (1, 2, 3, 4, 5, (6, 7)) n2: (1, 2, 3, 4, 5, (6, 7))
        print(id(n1),id(n4)) #10416584 10416584
        print(id(n1[5]),id(n4[5])) #18415304 18415304
        print(type(n1),type(5)) #<class 'tuple'> <class 'int'>

再一個小插曲:
        import copy
        n1 = (1,2,3,4,5,[6,7,],)
        #賦值
        n2 = n1
        print('n1:',n1,'n2:',n2) #(1, 2, 3, 4, 5, [6, 7]) n2: (1, 2, 3, 4, 5, [6, 7])
        print(id(n1),id(n2)) #11465160 11465160
        print(id(n1[5]),id(n2[5])) #18480456 18480456
        print(type(n1),type(2)) #<class 'tuple'> <class 'int'>
        #淺拷貝
        n3 = copy.copy(n1)
        print('n1:',n1,'n3:',n3) #n1: (1, 2, 3, 4, 5, [6, 7]) n3: (1, 2, 3, 4, 5, [6, 7])
        print(id(n1),id(n3)) #11465160 11465160
        print(id(n1[5]),id(n3[5])) #18480456 18480456
        print(type(n1),type(3)) #<class 'tuple'> <class 'int'>
        #深拷貝
        n4 = copy.deepcopy(n1)
        print('n1:',n1,'n4:',n4) #n1: (1, 2, 3, 4, 5, [6, 7]) n4: (1, 2, 3, 4, 5, [6, 7])
        print(id(n1),id(n4)) #11465160 18109736
        print(id(n1[5]),id(n4[5])) #18480456 18478920
        print(type(n1),type(5)) #<class 'tuple'> <class 'int'>    

出現以上問題有可能跟下面的說法有關:

案例代碼
    import copy
    dic = {
        "cpu":[80,],
        "mem":[80,],
        "disk":[80,],
    }

    print("old:",dic)
    new_dic1 = copy.copy(dic)
    new_dic1["cpu"][0] = 50
    print("old:",dic)
    print("淺拷貝:",new_dic1)
    #返回結果:
    #old: {'disk': [80], 'cpu': [80], 'mem': [80]}
    #淺拷貝: {'disk': [80], 'cpu': [50], 'mem': [80]}

    new_dic2 = copy.deepcopy(dic)
    new_dic2["cpu"][0] = 60
    print("old:",dic)
    print("深拷貝:",new_dic2)
    #返回結果
    # old: {'mem': [80], 'cpu': [50], 'disk': [80]}
    # 深拷貝: {'mem': [80], 'cpu': [60], 'disk': [80]}

4、函數

博客連接:http://www.cnblogs.com/songqingbo/p/5142957.html

定義:
    #!/usr/local/env python3
    '''
    Author:@南非波波
    Blog:http://www.cnblogs.com/songqingbo/
    E-mail:qingbo.song@gmail.com
    '''
    #定義函數,做用打印一個值
    def num_print():
        n = 456
        n += 1
        print(n)
使用: #函數調用 num_print() #將f變量指向函數num_print,而後調用f()至關於調用num_print() f = num_print f()

參數

形參:函數中一個變量,在函數執行前無心義,在函數調用時必須指定實際參數。
實參:實際參數用戶傳遞給所調用的函數的一個變量,其值賦值到函數中的形式參數,而後在函數中    做爲變量參與函數執行
默認參數:必須放在最後
    def show(a1,a2,a3 = 5):
        print(a1,a2,a3)
    show("wu","ha")
    #返回結果:wu ha 5

指定參數:
    def show(a1,a2):
        print(a1,a2)
    show(a2=52,a1=8)
    #返回結果:8 52

動態參數:
    *arg --序列:自動轉換成一個元組
        def show(*arg):
            print(arg,type(arg))
        show(23,45,67)
        #返回結果:(23, 45, 67) <class 'tuple'>
        #or
        l = [23,45,67]
        show(*l)
        #返回結果:(23, 45, 67) <class 'tuple'>

    **arg --字典:自動轉換成一個字典
        #默認字典處理
        def show(**arg):
            print(arg,type(arg))
        show(name1='swht',name2='shen')
        #返回結果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>
        #or
        d = {"name1"="swht","name2"="shen"}
        show(**d)
        #返回結果:{'name1': 'swht', 'name2': 'shen'} <class 'dict'>

    *arg,**kwarges --序列和字典
        def show(*args,**kwargs):
            print(args,type(args),'\n',kwargs,type(kwargs))
        show(23,45,67,82,name1='swht',name2='shen')
        #返回結果:(23, 45, 67, 82) <class 'tuple'> 
                  {'name2': 'shen', 'name1': 'swht'} <class 'dict'>     
        注意:使用*arg,**kwarges組合參數,必須是*arg在前,**kwarges在後,不然系統報錯;另外實參在輸入的時候也應該是按照上述順序。

拓展:

    def show(*args,**kwargs):
        print(args,type(args),'\n',kwargs,type(kwargs))
    l = [23,45,67,82]
    d = {'name1':'swht','name2':'shen'}
    show(l,d)
    #返回結果:
    ([23, 45, 67, 82], {'name1': 'swht', 'name2': 'shen'}) <class 'tuple'> 
    {} <class 'dict'>

    def show(*args,**kwargs):
        print(args,type(args),'\n',kwargs,type(kwargs))
    l = [23,45,67,82]
    d = {'name1':'swht','name2':'shen'}
    show(*l,**d)
    #返回結果:
    (23, 45, 67, 82) <class 'tuple'> 
    {'name2': 'shen', 'name1': 'swht'} <class 'dict'>

    總結:
        函數能夠傳遞元組、列表、字典等類型的值,因爲帶'*'、'**'的參數容許傳入多個參數,因此在調用函數的時候默認將傳入的參數識別到第一個*args。爲了指定將參數傳給某個args,這裏須要對實參進行加'*'進行標識。

    #list
    show = "Welcome to {0},there have too many {1}!"
    # reault = show.format("China","Foods")
    l = ["China","Foods"]
    reault = show.format(*l)
    print(reault)
    #返回結果:Welcome to China,there have too many Foods!

    #dict
    show = "{name} is a {acter}!"
    # reault = show.format(name='swht',acter='teacher')
    d = {'name':'swht','acter':'teacher'}
    reault = show.format(**d)
    print(reault)
    #返回結果:swht is a teacher!

  

lambda表達式

    功能:簡單函數的表示方式
    func = lambda a:a+1
    函數名  關鍵字 形參:函數體
    建立形式參數a,函數內容爲a+1,並將結果return
測試代碼:
    f = lambda x:x + 1
    ret = f(4)
    print(ret)

內置函數

abs()

    功能:取絕對值
    >>> abs(5)
    5
    >>> abs(-85)
    85

all(iterable)

    功能:iterable全部的元素都爲真,返回True,不然返回False
    備註:爲False的元素:0、''、False或者空,其餘的爲True
    參數:iterable爲可迭代對象
    all的功能可使用下面的函數進行理解:
        def all(iterable):
        for element in iterable:
            if not element:
                return False
        return True
    測試代碼:
        all('test,hh')
        返回值爲:True
        >>> all(['a', 'b', 'c', 'd'])  #列表list,元素都不爲空或0
        True
        >>> all(['a', 'b', '', 'd'])  #列表list,存在一個爲空的元素
        False
        >>> all([0, 1,2, 3])  #列表list,存在一個爲0的元素
        False             
        >>> all(('a', 'b', 'c', 'd'))  #元組tuple,元素都不爲空或0
        True
        >>> all(('a', 'b', '', 'd'))  #元組tuple,存在一個爲空的元素
        False
        >>> all((0, 1,2, 3))  #元組tuple,存在一個爲0的元素
        False
        >>> all([]) # 空列表
        True
        >>> all(()) # 空元組
        True    

any(iterable)

  功能:iterable中元素只要有一個元素爲真,則返回True,不然返回False(即iterable中全部的元素爲假纔會返回False)
    參數:iterable爲可迭代對象
    any的功能可使用下面的函數進行理解:
    def any(iterable):
       for element in iterable:
           if  element:
               return False
       return True
    測試代碼:
        >>> any([0,1,2,3]) #列表中僅有一個元素0爲假,返回True
        True
        >>> any([' ', '  ', '', 0])
        True
        >>> any([0]) #列表中元素只有一個元素0,返回False
        False
        >>> any([0,''])
        False
        >>> any([0,'',4])
        True    
        >>> any(('a', 'b', 'c', 'd'))  #元組tuple,元素都不爲空或0
        True
        >>> any(('a', 'b', '', 'd'))  #元組tuple,存在一個爲空的元素
        True
        >>> any((0, '', False))  #元組tuple,元素全爲0,'',false
        False
        >>> any([]) # 空列表
        False
        >>> any(()) # 空元組
        False

map(iterable)

    功能:對可迭代函數'iterable'中的每個元素應用‘function’方法,將結果做爲list返回
    參考連接:http://segmentfault.com/a/1190000000322433
    測試代碼:
        def add_100(num):
            return num + 100
        li1 = [25,26,27]
        ret = list(map(add_100,li1))
        print(ret)
        返回結果:[125, 126, 127]

python2.7                               python3.5
    兩個版本的對比,真是讓人感到詫異,python3上執行map明明已經獲取了值,但非得加個list進行展現,超乎尋常。

    def abc(a,b,c):
        return a*1000 + b*100 + c*10

    list1 = [11,22,33]
    list2 = [44,55,66]
    list3 = [77,88,99]
    ret = list(map(abc,list1,list2,list3))
    print(ret) #返回結果 [16170, 28380, 40590]

ascii(object)

    功能:該函數與python2中的repr()函數同樣,返回一個可打印的對象字符串。當遇到非ascii碼時,就會輸出\x,\u或\U等字符來表示。例如:ascii(4) = int.__repr__(4) = repr(4)等號兩邊的方式是對等的。
    測試代碼:
        >>> ascii(54)
        '54'
        >>> ascii('o')
        "'o'"
        >>> type(ascii(54))
        <class 'str'>   
        >>> print(ascii(10), ascii(9000000), ascii('b\31'), ascii('0x\1000'))
            10 9000000 'b\x19' '0x@0'

bin()

    功能:將整數轉換爲二進制字符串
    >>> bin(56)
    '0b111000'
    >>> bin(100)
    '0b1100100'
    注意:若是bin()函數的實際參數不是一個整數,則該該實參(由類建立的對象)返回值必須是整數型
    如:
    >>> class myType:
    ...     def __index__(self):
    ...             return 56
    ...
    >>> myvar = myType()
    >>> bin(myvar)
    '0b111000'

bool()

    功能:獲取對象的bool值
    bool(0) #False
    bool(5) #True
    bool('') #False
    #爲假的元素:0 none 空列表 空字典 空元組 空字符串

bytearray()

    功能:轉成字符字典。Bytearray類型是一個可變的序列,而且序列中的元素的取值範圍爲 [0 ,255]。
    >>> a = bytearray([5,8])
    >>> a[0]
    5
    >>> a[1]
    8
    >>> a
    bytearray(b'\x05\x08')

bytes()

    功能:返回一個新的數組對象,這個數組不能對數組元素進行修改,每一個元素的取值範圍爲[0 ,255]
    測試代碼:
    bytes(iterable_of_ints) 
        >>> b = bytes((5,8,6,8))
        >>> print(b)
        b'\x05\x08\x06\x08'
    bytes(string, encoding[, errors])   
        >>> bytes('sdjsd',encoding='utf-8')
        b'sdjsd'
    bytes(bytes_or_buffer)  ?
    bytes(int) 
        >>> bytes(5)
        b'\x00\x00\x00\x00\x00'
    bytes()  
        >>> bytes()
        b''
總結:(參考:http://blog.csdn.net/caimouse/article/details/40860827) bytes函數與bytearray函數主要區別是bytes函數產生的對象的元素不能修改,而bytearray函數產生的對象的元素能夠修改。所以,除了可修改的對象函數跟bytearray函數不同以外,其它使用方法所有是相同的。最後它的參數定義方式也與bytearray函數是同樣的。

callable()

    功能:判斷函數或者對象是否可執行
    >>> callable(5)
    False
    >>> callable(0)
    False
    >>> callable('')
    False
    >>> callable(int())
    False
    >>> callable(lambda x:x+1)
    True

chr()

    功能:參數爲一個整型數字,返回值對應ASCII碼的字符
    >>> chr(5)
    '\x05'
    >>> chr(115)
    's'
    >>> chr(56)
    '8'

ord()

    功能:返回一個字符的ASCII碼值
    >>> ord('s')
    115
    >>> ord('5')
    53

classmethod()

    功能:classmethod是用來指定一個類的方法爲類方法,沒有此參數指定的類的方法爲實例方法
    >>> class C: #定義一個類
    ...     @classmethod  #聲明爲類方法,不通過實例化就能夠直接調用
    ...     def f(self): #定義一個函數(類的方法)
    ...             print "This is a class method"
    ...
    >>> C.f()  #經過類調用函數
    This is a class method
    >>> c = C()
    >>> c.f()
    This is a class method
    >>> class D:
    ...     def f(self):
    ...             print " This is not a class method "
    ...
    >>> D.f()  #沒有通過@classmethod 聲明的類方法,必須通過實例化才能被調用
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
    >>> d = D()
    >>> d.f()
    This is not a class method

staticmethod()

    功能:類的靜態方法,只能在類內部使用。通過靜態類方法聲明的類,在調用的時候不須要進行實例化

總結:對比classmethod()和staticmethod()

    靜態方法:@staticmethod()
        class Foo(object):
            str = "I'm a static method."
            def bar():
                print(Foo.str)
            bar = staticmethod(bar)

        Foo.bar()
    返回結果:I'm a static method. 

    類方法:@classmethod()
        class Foo(object):
            str = "I'm a static method."
            def bar(cls):
                print(cls.str)
            bar = classmethod(bar)
        Foo.bar()
    返回結果:I'm a static method. 
較簡單的操做代碼:

    靜態方法:@staticmethod()
        class Foo:
            str = "I'm a static method."
            @staticmethod
            def bar():
                print(Foo.str)
        Foo.bar() 
    返回結果:I'm a static method. 

    類方法:@classmethod()
        class Foo:
            str = "I'm a static method."
            @classmethod
            def bar(cls):
                print(cls.str )
        Foo.bar()
    返回結果:I'm a static method.

compile()、eval()、exec()

    功能:compile語句是從type類型中將str裏面的語句建立成代碼對象。
        compile語句的目的是提供一次性的字節碼編譯,就不用在之後的每次調用中從新進行編譯了
    語法:compile( str, file, type )
        eveal_code = compile('1+2','','eval')
        >>>eveal_code
        返回結果:<code object <module> at 0x01555D40, file "", line 1>
        >>>eval(eveal_code)
        返回結果:3

        single_code = compile( 'print("apicloud.com")', '', 'single' )
        >>> single_code
        返回結果:<code object <module> at 0x01555B10, file "", line 1>
        >>> exec(single_code)
        返回結果:apicloud.com

complex()

    功能:建立一個值爲real + imag * j的複數或者轉化一個字符串或數爲複數。若是第一個參數爲字符串,則不須要指定第二個參數。
    參數real: int, long, float或字符串;
    參數imag: int, long, float
    >>>complex()
    0j
    #數字
    >>> complex(1,2)
    (1+2j)
    #當作字符串處理
    >>> complex('1')
    (1+0j)
    #注意:這個地方在「+」號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",不然會報錯
    >>> complex('1+2j')
    (1+2j)

delattr()

    參考連接:http://www.cnblogs.com/zhangjing0502/archive/2012/05/16/2503702.html
    功能:刪除object對象名爲name的屬性
    語法:delattr(object,name) 
    參數object:對象。
    參數name:屬性名稱字符串。

    >>> class Person:
    ...     def __init__(self, name, age):
    ...             self.name = name
    ...             self.age = age
    ...
    >>> tom = Person("Tom", 35)
    >>> dir(tom)
    ['__doc__', '__init__', '__module__', 'age', 'name']
    >>> delattr(tom, "age")
    >>> dir(tom)
    ['__doc__', '__init__', '__module__', 'name']

getattr()

    功能:用於返回一個對象屬性,或者方法
    class A:   
        def __init__(self):   
            self.name = 'zhangjing'  
        #self.age='24'
        def method(self):   
            print("method print")  

    Instance = A()   
    print(getattr(Instance , 'name', 'not find')) #若是Instance 對象中有屬性name則打印self.name的值,不然打印'not find'
    print(getattr(Instance , 'age', 'not find'))  #若是Instance 對象中有屬性age則打印self.age的值,不然打印'not find'
    print(getattr(a, 'method', 'default'))  
    #若是有方法method,不然打印其地址,不然打印default   
    print(getattr(a, 'method', 'default')()) 
    #若是有方法method,運行函數並打印None不然打印default

    li=["swht","shen"]
    getattr(li,"pop")
    返回結果:<built-in method pop of list object at 0x01AFDA80>

setattr()

    功能:參數是一個對象,一個字符串和一個任意值。字符串可能會列出一個現有的屬性或一個新的屬性。這個函數將值賦給屬性的。該對象容許它提供。
    語法:setattr(object, name, value) 
    setattr(x,「foobar」,123)至關於x.foobar = 123

hasattr()

    功能:用於肯定一個對象是否具備某個屬性
    語法:hasattr(object, name) -> bool
        判斷object中是否有name屬性,返回一個布爾值
    li=["swht","shen"]
    hasattr(li,'append')
    返回結果:True

dict()

    功能:字典定義函數,能夠建立一個字典,也能夠將其餘類型(列表、元組、字符串)轉換成字典類型
    定義:
        dict1 = dict(one = 1, two = 2, a = 3)
        prin(dict1)
        {'one': 1, 'a': 3, 'two': 2}
    類型轉換:
        list1 = ['name','age',]
        list2 = ['swht',18]
        dict(zip(list1,list2))
        返回結果:{'name': 'swht', 'age': 18}

        new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
        dict(new_list)
        返回結果:{'key3': 'value3', 'key1': 'value1', 'key2': 'value2'}

dir()

功能:查看函數或模塊內的操做方法都有什麼,輸出的是方法列表。
    如dir(int)能夠直接獲取int的全部方法,返回的類型是一個列表

divmod()

    功能:divmod(a,b)方法返回的是a//b(除法取整)以及a對b的餘數
    >>> divmod(2,5)
    (0, 2)
    >>> divmod(12,5)
    (2, 2)

enumerate()

    功能:獲取字典的索引值並指定開始值
    li = ['swht','shen','test']
    for i,k in enumerate(li,3): #遍歷列表,索引值從3開始
        print(i,k)
    #返回結果
    3 swht
    4 shen
    5 test

filter()

    參考連接:http://www.cnblogs.com/fangshenghui/p/3445469.html
    功能:filter(function, sequence)對於隊列中的item依次被function處理
    def fun(item):
        if item != 4:
            return item
    list1 = [5,4,8]
    print(list(filter(fun,list1)))
    返回結果:[4, 8]
    總結:至關於一個過濾函數

frozenset()

    參考:http://blog.csdn.net/caimouse/article/details/42042051
    功能:本函數是返回一個凍結的集合
    l = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]  
    print(len(l), l)  
    set = frozenset(l)  
    print(len(set), set) 
    返回結果:11 [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
             9 frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})
    總結:所謂凍結就是這個集合不能再添加或刪除任何集合裏的元素。所以與集合set的區別,就是set是能夠添加或刪除元素,而frozenset不行。frozenset的主要做用就是速度快,它是使用hash算法實現。參數iterable是表示可迭代的對象,好比列表、字典、元組等等

locals()、globals()

    功能:基於字典的訪問局部和全局變量的方式
    locals 是隻讀的,globals 不是
    關於名字空間的相關說明請移步參考:http://blog.csdn.net/scelong/article/details/6977867

hash()

    功能:輸出對象的hash值
    >>> hash(8)
    8
    >>> hash('sd')
    -584109415
    >>> hash('99')
    -1356598271
    >>> hash('asds')
    -1179125483

help()

功能:查看函數或模塊用途的詳細說明
    使用方法:help(object)

類型轉換

    int(x [,base ])         將x轉換爲一個整數    
    long(x [,base ])        將x轉換爲一個長整數    
    float(x )               將x轉換到一個浮點數    
    complex(real [,imag ])  建立一個複數    
    str(x )                 將對象 x 轉換爲字符串    
    repr(x )                將對象 x 轉換爲表達式字符串    
    eval(str )              用來計算在字符串中的有效Python表達式,並返回一個對象    
    tuple(s )               將序列 s 轉換爲一個元組    
    list(s )                將序列 s 轉換爲一個列表    
    chr(x )                 將一個整數轉換爲一個字符    
    unichr(x )              將一個整數轉換爲Unicode字符    
    ord(x )                 將一個字符轉換爲它的整數值    
    hex(x )                 將一個整數轉換爲一個十六進制字符串    
    oct(x )                 將一個整數轉換爲一個八進制字符串

id()

    功能:獲取對象的內存地址
    id(object)

input()

    功能:獲取用戶的輸入信息
    input("請輸入你的名字:")
    >>>請輸入你的名字:swht
    swht

isinstance()

    功能:判斷對象類型
    isinstance(5,int)
    返回結果:True

issubclass()

    功能:本函數用來判斷類參數class是不是類型參數classinfo的子類
    class Line:  
        pass  
    class RedLine(Line):  
        pass  

    class Rect:  
        pass  

    print(issubclass(RedLine, Line))  #返回True  Redline是Line的子類
    print(issubclass(Rect, Line))  #返回False  

iter()

    功能:建立一個迭代器
    for i in iter((1,2,4,5,6,7,)):
        print(i)
    返回結果:1 2 4 5 6 7 #循環遍歷元組

len()

    功能:獲取字符串的長度
    len(str)

max()

    功能:返回全部整數中最大的一個數
    max(5,6,8,7) 
    返回結果:8

memoryview()

    功能:本函數是返回對象obj的內存查看對象
    >>> v = memoryview(b'abc123')
    >>> print(v[1])
    98
    >>> print(v[0])
    97
    >>> print(v[2])
    import struct  
    buf = struct.pack("i"*12, *list(range(12)))  
    x = memoryview(buf)  
    y = x.cast('i', shape=[2,2,3])  
    print(y.tolist()) 
    返回結果:[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

    總結:所謂內存查看對象,就是對象符合緩衝區協議的對象,爲了給別的代碼使用緩衝區裏的數據,而沒必要拷貝,就能夠直接使用。參考連接:http://blog.csdn.net/caimouse/article/details/43083627

sorted()

    功能:排序
    sorted([5, 2, 3, 1, 4])
    [1, 2, 3, 4, 5]

sum()

    功能:返回整數數字的和
    sum([1,5,8]) #參數是一個list
    返回結果:14

super()

功能:用來解決多重繼承問題

type()

    功能:獲取對象的類型
    type(object)

vars()

    功能:本函數是實現返回對象object的屬性和屬性值的字典對象
    >>> class Foo:
    ...     a = 1
    ...
    >>> print(vars(Foo))
    {'a': 1, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__doc__': None, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__module__': '__main__'}

    總結:若是默認不輸入參數,就打印當前調用位置的屬性和屬性值,至關於locals()的功能。若是有參數輸入,就只打印這個參數相應的屬性和屬性值。參考:http://blog.csdn.net/caimouse/article/details/46489079

zip()

    功能:zip函數接受任意多個(包括0個和1個)序列做爲參數,返回一個tuple列表
    >>> x = [1,2,3,]
    >>> y = [4,5,6,]
    >>> z = [7,8,9,]
    >>> xyz = zip(x,y,z)
    >>> print(xyz)
    <zip object at 0x00FBD968>
    >>> print(list(xyz))
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

random

    功能:產生隨機數
    import random
    random.randint(1,99) #從1-99中產生隨機數

import()

    功能:查看模塊所在的位置
     __import__('random') #參數爲一個字符串
    <module 'random' from 'D:\\Program Files\\Python\\Python35\\python35.zip\\random.pyc'>

open()函數

博客參考:http://www.cnblogs.com/songqingbo/p/5102618.html

read()

功能:讀取文件中的全部內容,返回的類型是字節

readline()

功能:讀取文件中的一行數據。返回的類型是字節

readlines()

功能:讀取文件中的全部內容,返回的類型是list

tell()

功能:查看當前指針位置,返回值類型爲整數

seek()

功能:指定當前指針位置


files = open('test.txt','r',encoding='utf-8')
files.seek(5)
print(files.read()) #讀取指爲直接切割針5後面的全部字符
files.truncate() #獲取指針5以前的全部字符而後寫到原來的文件(或者能夠理解)
files.close()

擴展

讀二進制文件:

    input = open('data','rb')

讀取全部內容:

    f = open('test.txt','r')
    try:
        all_txt_view = f.read()
    finally:
        f.close()

讀取固定字節:

    f = open('test.txt','rb')
    try:
        while True:
            chunk = f.read(100)
            if not chunk:
                break
            pass
    finally:
        f.close()

讀每行:

    list_of_all_the_lines = f.readlines()

若是文件是文本文件,還能夠直接遍歷文件對象獲取每行:

    for line in f:
        print(line)

寫文件寫文本文件

    output = open('data','w')

寫入多行:

    f.writeline(list_of_text_string)

做業:

做業鏈接:http://www.cnblogs.com/wupeiqi/articles/4950799.html
1. 用戶輸入一個字符串,將其轉換成字典 使用json
2. 增長一條記錄
3. (可選)刪除一條
4. (可選)線上文件修改


global       
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend test.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
        #server 100.1.7.9 100.1.7.999 weight 20 maxconn 3000


backend buy.oldboy.org
        server 100.1.7.90 100.1.7.90 weight 20 maxconn 3000

字典:     
{"backend": "test.oldboy.org",
 "record":{
        "server": "100.1.7.999",
        "weight": 20,
        "maxconn": 30
  }
}

 做業源碼博客地址:http://www.cnblogs.com/songqingbo/p/5149909.html

相關文章
相關標籤/搜索