第三篇 python進階 二

一、collection系列
1、計數器(counter)
collection是對字典中重複字符出現的次數,其具備字典的所有功能加自己的功能相對與包含字典。
舉例:

#!/usr/bin/env  python
# --*--coding:utf-8 --*--
import collections
c = collections.Counter("sdsasdsa") 
print c

輸出結果是:

Counter({'s': 4, 'a': 2, 'd': 2})

如果說提取裏面的值就需要用到

b = collections.Counter('aswedswedswedswed')
print b
b.update(c) #把c添加到b裏面
print b

輸出結果是:

Counter({'s': 4, 'a': 2, 'd': 2})
Counter({'s': 4, 'e': 4, 'd': 4, 'w': 4, 'a': 1})
Counter({'s': 8, 'd': 6, 'e': 4, 'w': 4, 'a': 3})
import collections
c = collections.Counter("sdsasdsa") #打印出後面重複的字符串
print c
print c.most_common(3) #顯示前幾個
輸出結果是:
Counter({'s': 4, 'a': 2, 'd': 2})
[('s', 4), ('a', 2), ('d', 2)]
print sorted(b) #按順序打印元素
print b

輸出結果是:

Counter({'s': 4, 'e': 4, 'd': 4, 'w': 4, 'a': 1})
['a', 'd', 'e', 's', 'w']

2、默認字典(defaultdict)
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],將所有大於 66 的值保存至字典的第一個key中,將小於 66 的值保存至第二個key的值中。
即: {'k1': 大於66 , 'k2': 小於66}

from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = defaultdict(list)
for value in  values:
    if value>66:
         my_dict['k1'].append(value)
    else:
         my_dict['k2'].append(value)
print my_dict

輸出結果是:

defaultdict(<type 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})

3、有序字典(orderedDict )
記住了字典元素的添加順序,進行排序

from collections import OrderedDict
a = {'a':1 , 'b':2 , 'c': 3}
print OrderedDict(sorted(a.items(), key=lambda t: t[1]))
print OrderedDict(sorted(a.items(), key=lambda t: len(t[0])))
print OrderedDict(sorted(a.items(), key=lambda t: t[1]))

輸出結果是:

OrderedDict([('a', 1), ('b', 2), ('c', 3)])
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

4、可命名元組(namedtuple)
根據nametuple可以創建一個包含tuple所有功能以及其他功能的類型,可命名元組

Mytuple = collections.namedtuple('Mytuple',['x', 'y'])    #新建元組
old = Mytuple(1, 2)
print old
new = Mytuple(1,2)
print new

輸出結果是:

Mytuple(x=1, y=2)
Mytuple(x=1, y=2)

5、雙向隊列(deque)
#線程安全的雙向隊列

q = collections.deque() #加雙向隊列
q.append(11)    #添加隊列
q.append(12)
q.append(13)
print q
print q.popleft() #左邊取值
print q.pop() #右邊取值

#單向隊列,隊列FIFO ,棧,彈夾

import Queue    #模塊
q = Queue.Queue()
q.put(1) #價值
q.put(2)
q.put(3)
print q.get(1)    #取值

#vars() = 當前模塊的所有變量

# print vars()
# {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'D:/s11day2/s11day2/coll.py', '__package__': None, 'collections': <module 'collections' from 'D:\Python27\Lib\collections.pyc'>, '__name__': '__main__', '__doc__': None}

二、內置函數
內置函數就是,python內部已經定義好的函數
all(值) #當值都是真的時候,返回真,否則返回假
any()   #只要有一個真,全爲真,否則爲假

>>> li = ['as', 'aa', '']
>>> any(li)
True
>>> all(li)
False
>>> li = ['as', 'aa', 'as']
>>> all(li)
True
>>> any(li)
True
>>> li = ['', '', '']
>>> any(li)
False
for k,v in enumerate(li, 起始值)
    print k,v

三、自定義函數
自己寫好的函數,在用的時候調用,不用的時候不執行
#郵件報警

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
def email(message): #收件人可以是一個列表多個參數receiver
    msg = MIMEText(message, 'plain', 'utf-8')
    msg['From'] = formataddr(["發件者姓名",'發件郵箱'])
    msg['To'] = formataddr(["收件者姓名",'收件箱'])
    msg['Subject'] = "主題"
    server = smtplib.SMTP("smtp.qq.com", 25)
    server.login("發件郵箱", "密碼")
    server.sendmail('發件郵箱', ['收件箱',], msg.as_string())
    server.quit()

#收件人可以是一個列表多個參數receiver
#在加一個for循環

if __name__ == '__main__':
    cpu = 90
    disk = 100
    ram = 50
    for i in range(1):
        if cpu > 80:
            alert = u"CPU報警"
            email(alert)
        if disk > 120:
            alert = u"disk報警"
            emial(alert)
        if ram > 20:
            alert = u"內存報警"
            email(alert)

四、動態參數

圖解:

wKioL1ZGma7A2ROlAAAwGTs9Ucc106.png

>>> def func(*arg):
...     print arg
...
>>> func()
()
>>> func(1)
(1,)
>>> func(1,2)
(1, 2)
>>> func(1,2,3)
(1, 2, 3)
>>> li = (11,22,33,44,55,66)
>>> func(li)
((11, 22, 33, 44, 55, 66),)
>>> func(*li)
(11, 22, 33, 44, 55, 66)

1、接受多個參數
2、內部自動構造元組
3、序列,*,避免內部構造元組
加一個*內部構造是元組,兩個**kwargs是構造字典,傳入的時候要func(k1=123,k2=124),傳入字典

func(**dic)
>>> def func(**kwargs):
...     print kwargs
...
>>> func()
{}
>>> func(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes exactly 0 arguments (1 given)
>>> func(k1=123,k2=234)
{'k2': 234, 'k1': 123}
>>> ls = {'k1':233, 'k2':345}
>>> func(**ls)
{'k2': 345, 'k1': 233}

兩個動態函數結合







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章