标签:
1 dict1 = {} 2 dict1[‘k1‘] = ‘v1‘ 3 4 list1 = [] 5 list1.append(‘v1‘)
1 Python 2.7.6 (default, Mar 22 2014, 22:59:56) 2 [GCC 4.8.2] on linux2 3 Type "help", "copyright", "credits" or "license" for more information. 4 >>> import collections 5 >>> c1 = collections.Counter() 6 >>> str1 = ‘fujafksabfaskfjaslfl jshjfkk fhsfj hfajsjfsk fj‘ 7 >>> c1 = collections.Counter(str1) 8 >>> c1 # 对于字符串操作的结果是:为每个出现的字符计数 9 Counter({‘f‘: 11, ‘j‘: 8, ‘s‘: 7, ‘a‘: 5, ‘k‘: 5, ‘ ‘: 4, ‘h‘: 3, ‘l‘: 2, ‘b‘: 1, ‘u‘: 1}) 10 >>> list1 = [11,22,22,33,33,33,44,44,44,44] 11 >>> c1 = collections.Counter(list1) 12 >>> c1 # 对于列表操作的结果是:为每个出现的元素计数 13 Counter({44: 4, 33: 3, 22: 2, 11: 1}) 14 >>>
2,有序字典 orderedDict
1 dic ={} 2 dic = {‘k1‘:[]} # → 这两行等同于下例中的一行(#←) 3 dic[‘k1‘].append(1) # → 这两行等同于下例中的一行(#←)
1 from collections import defaultdict 2 dic = collections.defaultdict(list) # ← 3 dic[‘k1‘].append(1)
1 >>> from collections import defaultdict # 使用默认字典,需要先导入defaultdict 2 >>> dic = {} 3 >>> dic = collections.defaultdict(list) # 创建一个默认字典对象,把字典的value的默认类型置为列表 4 >>> dic[‘k1‘].append(1) # 向字典中添加一个key k1<list类型>,并向k1中append一个元素1 5 >>> dic 6 defaultdict(<type ‘list‘>, {‘k1‘: [1]}) 7 >>> 8 >>> dic1 = {‘k1‘:1} 9 >>> dic1 10 {‘k1‘: 1} 11 >>> 12 >>> dic1 = collections.defaultdict(list) 13 >>> dic1 14 defaultdict(<type ‘list‘>, {}) 15 >>> 16 >>> dic1.append(22) # 直接对dict1做append操作会报错,因为字典不能通过append进行赋值 17 Traceback (most recent call last): 18 File "<stdin>", line 1, in <module> 19 AttributeError: ‘collections.defaultdict‘ object has no attribute ‘append‘ 20 >>> dic1[‘k2‘].append(22) # 可以对默认字典中的列表元素做append操作 21 >>> dic1 22 defaultdict(<type ‘list‘>, {‘k2‘: [22]}) 23 >>>
1 >>> Mytuple = collections.namedtuple(‘Mytuple‘,[‘x‘,‘y‘]) 2 >>> 3 >>> n = Mytuple(x=1,y=2) 4 >>> n.x 5 1 6 >>> n.y 7 2 8 >>>
1 Help on class Mytuple in module __main__: 2 3 class Mytuple(__builtin__.tuple) 4 | Mytuple(x, y) 5 | 6 | Method resolution order: 7 | Mytuple 8 | __builtin__.tuple 9 | __builtin__.object 10 | 11 | Methods defined here: 12 | 13 | __getnewargs__(self) 14 | Return self as a plain tuple. Used by copy and pickle. 15 | 16 | __getstate__(self) 17 | Exclude the OrderedDict from pickling 18 | 19 | __repr__(self) 20 | Return a nicely formatted representation string 21 | 22 | _asdict(self) 23 | Return a new OrderedDict which maps field names to their values 24 | 25 | _replace(_self, **kwds) 26 | Return a new Mytuple object replacing specified fields with new values 27 | 28 | ---------------------------------------------------------------------- 29 | Class methods defined here: 30 | 31 | _make(cls, iterable, new=<built-in method __new__ of type object>, len=<built-in function len>) from __builtin__.type 32 | Make a new Mytuple object from a sequence or iterable 33 | 34 | ---------------------------------------------------------------------- 35 | Static methods defined here: 36 | 37 | __new__(_cls, x, y) 38 | Create new instance of Mytuple(x, y) 39 | 40 | ---------------------------------------------------------------------- 41 | Data descriptors defined here: 42 | 43 | __dict__ 44 | Return a new OrderedDict which maps field names to their values 45 | 46 | x 47 | Alias for field number 0 48 | 49 | y 50 | Alias for field number 1 51 | 52 | ---------------------------------------------------------------------- 53 | Data and other attributes defined here: 54 | 55 | _fields = (‘x‘, ‘y‘) 56 | 57 | ---------------------------------------------------------------------- 58 | Methods inherited from __builtin__.tuple: 59 | 60 | __add__(...) 61 | x.__add__(y) <==> x+y 62 | 63 | __contains__(...) 64 | x.__contains__(y) <==> y in x 65 | 66 | __eq__(...) 67 | x.__eq__(y) <==> x==y 68 | 69 | __ge__(...) 70 | x.__ge__(y) <==> x>=y 71 | 72 | __getattribute__(...) 73 | x.__getattribute__(‘name‘) <==> x.name 74 | 75 | __getitem__(...) 76 | x.__getitem__(y) <==> x[y] 77 | 78 | __getslice__(...) 79 | x.__getslice__(i, j) <==> x[i:j] 80 | 81 | Use of negative indices is not supported. 82 | 83 | __gt__(...) 84 | x.__gt__(y) <==> x>y 85 | 86 | __hash__(...) 87 | x.__hash__() <==> hash(x) 88 | 89 | __iter__(...) 90 | x.__iter__() <==> iter(x) 91 | 92 | __le__(...) 93 | x.__le__(y) <==> x<=y 94 | 95 | __len__(...) 96 | x.__len__() <==> len(x) 97 | 98 | __lt__(...) 99 | x.__lt__(y) <==> x<y 100 | 101 | __mul__(...) 102 | x.__mul__(n) <==> x*n 103 | 104 | __ne__(...) 105 | x.__ne__(y) <==> x!=y 106 | 107 | __rmul__(...) 108 | x.__rmul__(n) <==> n*x 109 | 110 | __sizeof__(...) 111 | T.__sizeof__() -- size of T in memory, in bytes 112 | 113 | count(...) 114 | T.count(value) -> integer -- return number of occurrences of value 115 | 116 | index(...) 117 | T.index(value, [start, [stop]]) -> integer -- return first index of value. 118 | Raises ValueError if the value is not present. 119 (END)
1 >>> import collections 2 >>> q = collections.deque() 3 >>> q.append(1) 4 >>> q.append(2) 5 >>> q.append(3) 6 >>> q.append(4) 7 >>> 8 >>> q 9 deque([1, 2, 3, 4]) 10 >>> q.pop() 11 4 12 >>> q 13 deque([1, 2, 3]) 14 >>> q.popleft() # 此处要注意,是popleft而非leftpop 15 1 16 >>> q 17 deque([2, 3]) 18 >>> 19 >>> q.appendleft(5) 20 >>> q 21 deque([5, 2, 3]) 22 >>>
1 >>> import Queue 2 >>> 3 >>> q = Queue.Queue(10) 4 >>> 5 >>> q.put(1) 6 >>> q.put(2) 7 >>> q.put(3) 8 >>> q 9 <Queue.Queue instance at 0x7f3975f505a8> 10 # 此处返回的是这个对象实例的内存地址 11 # 之所以没有返回队列中所有的元素是因为 12 # 在Queue的类的定义中没有实现__str__的方法。 13 >>> q.get() 14 1 15 >>> q.get() 16 2 17 >>> q.get() 18 3 19 >>> q.get() # 此时队列里已经没有元素了,再get则会hang住。 20 21 22 23 24 ^C^C
1 >>> dir(list) 2 [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__delslice__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__setslice__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘] 3 >>> 4 >>> help(list.__iter__) 5 6 7 Help on wrapper_descriptor: 8 9 __iter__(...) 10 x.__iter__() <==> iter(x) 11 (END)
1 # 方法1 2 >>> li = [11,22,33,44,55,66] 3 >>> for i in li: 4 ... print i 5 ... 6 11 7 22 8 33 9 44 10 55 11 66 12 >>> 13 # 方法2 14 >>> li = [11,22,33,44,55,66] 15 >>> for i in range(len(li)): 16 ... print li[i] 17 ... 18 11 19 22 20 33 21 44 22 55 23 66 24 >>>
1 >>> 2 >>> range(10) 3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 4 >>> 5 >>> xrange(10) 6 xrange(10) 7 >>>
1 # 基于range的冒泡排序算法 2 li = [13, 22, 6, 99, 11] 3 4 for m in range(len(li)-1): 5 6 for n in range(m+1, len(li)): 7 if li[m]> li[n]: 8 temp = li[n] 9 li[n] = li[m] 10 li[m] = temp 11 12 print li
1 >>> li = [‘stephen‘,‘‘,25] 2 >>> all(li) 3 False 4 >>> any(li) 5 True 6 >>> 7 >>> li = [‘stephen‘,‘password‘,25] 8 >>> all(li) 9 True 10 >>> any(li) 11 True 12 >>> 13 >>> li = [‘‘] 14 >>> all(li) 15 False 16 >>> any(li) 17 False 18 >>> 19 >>>
1 >>> li = [11,22,33,44,55,66] 2 >>> for k,v in enumerate(li): 3 ... print k,v 4 ... 5 0 11 6 1 22 7 2 33 8 3 44 9 4 55 10 5 66 11 >>> 12 >>> for k,v in enumerate(li,1): 13 ... print k,v 14 ... 15 1 11 16 2 22 17 3 33 18 4 44 19 5 55 20 6 66 21 >>> 22 >>>
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 __author__ = ‘Stephen‘ 4 5 def email(arg): 6 #print arg 7 8 if __name__ == ‘__main__‘: 9 cpu = 99 10 ram = 50 11 disk = 95 12 13 for i in range(1): 14 if cpu > 90: 15 alert = ‘cpu is ERROR‘ 16 email(alert) 17 if ram > 90: 18 alert = ‘memory is ERROR‘ 19 email(alert) 20 if disk > 90: 21 alert = ‘disk is ERROR‘ 22 email(alert)
C:\Python27\python.exe G:/python/day03/def_function.py cpu is ERROR disk is ERROR Process finished with exit code 0
修改为smtp的方式
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 __author__ = ‘Stephen‘ 4 5 import smtplib 6 from email.mime.text import MIMEText 7 from email.utils import formataddr 8 9 def email(arg): # 此处的arg为形式参数,简称形参。不赋值的时候没有实际意义。 10 msg = MIMEText(‘邮件内容‘, ‘plain‘, ‘utf-8‘) 11 msg[‘From‘] = formataddr(["Stephen",‘xxx@126.com‘]) 12 msg[‘To‘] = formataddr(["thatsit",‘xxx@qq.com‘]) 13 msg[‘Subject‘] = "监控报警邮件" 14 15 server = smtplib.SMTP("smtp.126.com", 25) 16 server.login("mail-address@126.com", "PASSWORD") 17 server.sendmail(‘xxx@126.com‘, [‘xxx@qq.com‘,], msg.as_string()) 18 server.quit() 19 20 21 if __name__ == ‘__main__‘: 22 cpu = 99 23 ram = 50 24 disk = 95 25 26 for i in range(10): 27 if cpu > 90: 28 alert = ‘cpu is ERROR 第%d次‘ %i 29 email(alert) # 此处的alert在赋值之后就是实际参数。 30 if ram > 90: 31 alert = ‘memory is ERROR 第%d次‘ %i 32 email(alert) 33 if disk > 90: 34 alert = ‘disk is ERROR 第%d次‘ %i 35 email(alert)
1 def func(**kwargs): 2 print kwargs 3 4 func (k1=123,k2=‘sss‘) 5 6 dic = {k1:123,k2:234} 7 func (**dic)
1 r,只读 2 w,清空原文件写 3 a,可读,可写,只能以追加的方式写 4 5 r+,可读可写 6 w+ <==> w 7 a+ <==> a
1 obj = open(‘log.txt‘,‘r‘) # 打开文件
2 obj.seek(5) # 指定文件的指针
3 print obj.tell() # 显示文件指针
4 obj.read() # 将文件全部加载到内存,此时的文件指针已经到了文件的尾部
5 print obj.tell() # 显示文件指针
执行结果:
C:\Python27\python.exe G:/python/day03/func.py
5
24
Process finished with exit code 0
1 truncate() # 根据当前指针的位置截断数据,截断位置也可以使用参数指定。 2 # eg:truncate(5) 3 4 b # 二进制,在linux没有什么卵用,在跨平台的时候要用。 5 rU # U参数只能跟r结合。写法有rU和r+U两种。 6 # 用来处理不同平台的换行符的问题:处理不同平台的换行符的问题:(\n,\r,\r\n)。 7 8 9 托管资源:手动进行释放,在python中才有,用于同时打开同一个文件。 10 非托管资源: 11 12 closed() #关闭文件 13 flush() # 会把应用缓存写到系统缓存中,但是不一定会直接写到磁盘,依赖于系统机制 14 15 open() #打开文件: 16 next() # 取下一行,不存在会报错。 17 write() # 写文件 18 writelines() # 参数可以是一个列表 19 xreadlines() # 逐行读取文件 20 for line in f: # 用来替换for line in f.xreadlines()
1 obj = open(‘log‘,‘r‘) 2 with open(‘log‘,‘r‘) as obj:
标签:
原文地址:http://www.cnblogs.com/thatsit/p/4985012.html