python之路:进阶 二
一、collection系列 |
1、计数器(counter)
collection是对字典中重复字符出现的次数,其具备字典的所有功能加自己的功能相对与包含字典。
举例:
1 #!/usr/bin/env python
2 # --*--coding:utf-8 --*--
3 import collections
4 c = collections.Counter("sdsasdsa")
5 print c
2 # --*--coding:utf-8 --*--
3 import collections
4 c = collections.Counter("sdsasdsa")
5 print c
输出结果是:
1 Counter({'s': 4, 'a': 2, 'd': 2})
如果说提取里面的值就需要用到
1 b = collections.Counter('aswedswedswedswed')
2 print b
3 b.update(c) #把c添加到b里面
4 print b
2 print b
3 b.update(c) #把c添加到b里面
4 print b
输出结果是:
1 Counter({'s': 4, 'a': 2, 'd': 2})
2 Counter({'s': 4, 'e': 4, 'd': 4, 'w': 4, 'a': 1})
3 Counter({'s': 8, 'd': 6, 'e': 4, 'w': 4, 'a': 3})
2 Counter({'s': 4, 'e': 4, 'd': 4, 'w': 4, 'a': 1})
3 Counter({'s': 8, 'd': 6, 'e': 4, 'w': 4, 'a': 3})
1 import collections
2 c = collections.Counter("sdsasdsa") #打印出后面重复的字符串
3 print c
4 print c.most_common(3) #显示前几个
2 c = collections.Counter("sdsasdsa") #打印出后面重复的字符串
3 print c
4 print c.most_common(3) #显示前几个
输出结果是:
1 Counter({'s': 4, 'a': 2, 'd': 2})
2 [('s', 4), ('a', 2), ('d', 2)]
2 [('s', 4), ('a', 2), ('d', 2)]
1 print sorted(b) #按顺序打印元素
2 print b
2 print b
输出结果是:
1 Counter({'s': 4, 'e': 4, 'd': 4, 'w': 4, 'a': 1})
2 ['a', 'd', 'e', 's', 'w']
2 ['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}
1 from collections import defaultdict
2 values = [11, 22, 33,44,55,66,77,88,99,90]
3 my_dict = defaultdict(list)
4 for value in values:
5 if value>66:
6 my_dict['k1'].append(value)
7 else:
8 my_dict['k2'].append(value)
9 print my_dict
2 values = [11, 22, 33,44,55,66,77,88,99,90]
3 my_dict = defaultdict(list)
4 for value in values:
5 if value>66:
6 my_dict['k1'].append(value)
7 else:
8 my_dict['k2'].append(value)
9 print my_dict
输出结果是:
defaultdict(<type 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})
3、有序字典(orderedDict )
记住了字典元素的添加顺序,进行排序
1 from collections import OrderedDict
2 a = {'a':1 , 'b':2 , 'c': 3}
3 print OrderedDict(sorted(a.items(), key=lambda t: t[1]))
4 print OrderedDict(sorted(a.items(), key=lambda t: len(t[0])))
5 print OrderedDict(sorted(a.items(), key=lambda t: t[1]))
2 a = {'a':1 , 'b':2 , 'c': 3}
3 print OrderedDict(sorted(a.items(), key=lambda t: t[1]))
4 print OrderedDict(sorted(a.items(), key=lambda t: len(t[0])))
5 print OrderedDict(sorted(a.items(), key=lambda t: t[1]))
输出结果是:
1 OrderedDict([('a', 1), ('b', 2), ('c', 3)])
2 OrderedDict([('a', 1), ('c', 3), ('b', 2)])
3 OrderedDict([('a', 1), ('b', 2), ('c', 3)])
2 OrderedDict([('a', 1), ('c', 3), ('b', 2)])
3 OrderedDict([('a', 1), ('b', 2), ('c', 3)])
4、可命名元组(namedtuple)
根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型,可命名元组
1 Mytuple = collections.namedtuple('Mytuple',['x', 'y']) #新建元组
2 old = Mytuple(1, 2)
3 print old
4 new = Mytuple(1,2)
5 print new
2 old = Mytuple(1, 2)
3 print old
4 new = Mytuple(1,2)
5 print new
输出结果是:
1 Mytuple(x=1, y=2)
2 Mytuple(x=1, y=2)
2 Mytuple(x=1, y=2)
5、双向队列(deque)
#线程安全的双向队列
1 q = collections.deque() #加双向队列
2 q.append(11) #添加队列
3 q.append(12)
4 q.append(13)
5 print q
6 print q.popleft() #左边取值
7 print q.pop() #右边取值
2 q.append(11) #添加队列
3 q.append(12)
4 q.append(13)
5 print q
6 print q.popleft() #左边取值
7 print q.pop() #右边取值
#单向队列,队列FIFO ,栈,弹夹
1 import Queue #模块
2 q = Queue.Queue()
3 q.put(1) #价值
4 q.put(2)
5 q.put(3)
6 print q.get(1) #取值
2 q = Queue.Queue()
3 q.put(1) #价值
4 q.put(2)
5 q.put(3)
6 print q.get(1) #取值
#vars() = 当前模块的所有变量
1 # print vars()
2 # {'__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}
2 # {'__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() #只要有一个真,全为真,否则为假
1 >>> li = ['as', 'aa', '']
2 >>> any(li)
3 True
4 >>> all(li)
5 False
6 >>> li = ['as', 'aa', 'as']
7 >>> all(li)
8 True
9 >>> any(li)
10 True
11 >>> li = ['', '', '']
12 >>> any(li)
13 False
14 for k,v in enumerate(li, 起始值)
15 print k,v
2 >>> any(li)
3 True
4 >>> all(li)
5 False
6 >>> li = ['as', 'aa', 'as']
7 >>> all(li)
8 True
9 >>> any(li)
10 True
11 >>> li = ['', '', '']
12 >>> any(li)
13 False
14 for k,v in enumerate(li, 起始值)
15 print k,v
三、自定义函数 |
自己写好的函数,在用的时候调用,不用的时候不执行
#邮件报警
1 import smtplib
2 from email.mime.text import MIMEText
3 from email.utils import formataddr
4 def email(message): #收件人可以是一个列表多个参数receiver
5 msg = MIMEText(message, 'plain', 'utf-8')
6 msg['From'] = formataddr(["发件者姓名",'发件邮箱'])
7 msg['To'] = formataddr(["收件者姓名",'收件箱'])
8 msg['Subject'] = "主题"
9 server = smtplib.SMTP("smtp.qq.com", 25)
10 server.login("发件邮箱", "密码")
11 server.sendmail('发件邮箱', ['收件箱',], msg.as_string())
12 server.quit()
2 from email.mime.text import MIMEText
3 from email.utils import formataddr
4 def email(message): #收件人可以是一个列表多个参数receiver
5 msg = MIMEText(message, 'plain', 'utf-8')
6 msg['From'] = formataddr(["发件者姓名",'发件邮箱'])
7 msg['To'] = formataddr(["收件者姓名",'收件箱'])
8 msg['Subject'] = "主题"
9 server = smtplib.SMTP("smtp.qq.com", 25)
10 server.login("发件邮箱", "密码")
11 server.sendmail('发件邮箱', ['收件箱',], msg.as_string())
12 server.quit()
#收件人可以是一个列表多个参数receiver
#在加一个for循环
1 if __name__ == '__main__':
2 cpu = 90
3 disk = 100
4 ram = 50
5 for i in range(1):
6 if cpu > 80:
7 alert = u"CPU报警"
8 email(alert)
9 if disk > 120:
10 alert = u"disk报警"
11 emial(alert)
12 if ram > 20:
13 alert = u"内存报警"
14 email(alert)
2 cpu = 90
3 disk = 100
4 ram = 50
5 for i in range(1):
6 if cpu > 80:
7 alert = u"CPU报警"
8 email(alert)
9 if disk > 120:
10 alert = u"disk报警"
11 emial(alert)
12 if ram > 20:
13 alert = u"内存报警"
14 email(alert)
四、动态参数 |
图解:
1 >>> def func(*arg):
2 ... print arg
3 ...
4 >>> func()
5 ()
6 >>> func(1)
7 (1,)
8 >>> func(1,2)
9 (1, 2)
10 >>> func(1,2,3)
11 (1, 2, 3)
12 >>> li = (11,22,33,44,55,66)
13 >>> func(li)
14 ((11, 22, 33, 44, 55, 66),)
15 >>> func(*li)
16 (11, 22, 33, 44, 55, 66)
2 ... print arg
3 ...
4 >>> func()
5 ()
6 >>> func(1)
7 (1,)
8 >>> func(1,2)
9 (1, 2)
10 >>> func(1,2,3)
11 (1, 2, 3)
12 >>> li = (11,22,33,44,55,66)
13 >>> func(li)
14 ((11, 22, 33, 44, 55, 66),)
15 >>> func(*li)
16 (11, 22, 33, 44, 55, 66)
1、接受多个参数
2、内部自动构造元组
3、序列,*,避免内部构造元组
加一个*内部构造是元组,两个**kwargs是构造字典,传入的时候要func(k1=123,k2=124),传入字典
1 func(**dic)
2 >>> def func(**kwargs):
3 ... print kwargs
4 ...
5 >>> func()
6 {}
7 >>> func(123)
8 Traceback (most recent call last):
9 File "<stdin>", line 1, in <module>
10 TypeError: func() takes exactly 0 arguments (1 given)
11 >>> func(k1=123,k2=234)
12 {'k2': 234, 'k1': 123}
13 >>> ls = {'k1':233, 'k2':345}
14 >>> func(**ls)
15 {'k2': 345, 'k1': 233}
2 >>> def func(**kwargs):
3 ... print kwargs
4 ...
5 >>> func()
6 {}
7 >>> func(123)
8 Traceback (most recent call last):
9 File "<stdin>", line 1, in <module>
10 TypeError: func() takes exactly 0 arguments (1 given)
11 >>> func(k1=123,k2=234)
12 {'k2': 234, 'k1': 123}
13 >>> ls = {'k1':233, 'k2':345}
14 >>> func(**ls)
15 {'k2': 345, 'k1': 233}
两个动态函数结合