标签:
==>the start
复习day2内容
介绍set()-->归档到day2了...
collections模块常用类
深浅copy的区别
自定义函数
文件操作
常用内建函数介绍
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 深浅copy的区别 7 """ 8 9 import copy 10 # 数字、字符串:赋值、浅拷贝和深拷贝无差别,因为其永远指向同一个内存地址。 11 print("字符串的赋值".center(30, ‘*‘)) 12 n1 = 123123 13 n2 = n1 14 print(id(n1)) 15 print(id(n2)) 16 17 print("字符串的赋值".center(30, ‘*‘)) 18 n11 = ‘123123‘ 19 n22 = n11 20 print(id(n11)) 21 print(id(n22)) 22 23 print("数字和字符串的浅copy".center(50, ‘*‘)) 24 n3 = copy.copy(n1) 25 print(id(n1)) 26 print(id(n3)) 27 28 print("数字和字符串的深copy".center(50, ‘*‘)) 29 n4 = copy.deepcopy(n1) 30 print(id(n1)) 31 print(id(n4)) 32 33 # 其他:除了数字和字符串以外,(多层)列表、字典、元祖等在进行赋值、浅copy、深copy时,内存地址是有区别的。 34 print("其他类的赋值".center(50, ‘*‘)) 35 m1 = {‘k1‘: 123, ‘k2‘: ‘123‘, ‘k3‘: [1, 3, 5]} 36 m2 = m1 37 print(id(m1)) 38 print(id(m2)) 39 40 print("其他类的浅拷贝".center(50, ‘*‘)) 41 print("浅copy".center(50, ‘*‘)) 42 m3 = copy.copy(m1) 43 print("id(m1):%s" % id(m1)) 44 print("id(m3):%s" % id(m3)) 45 # 浅拷贝的m3[‘k3‘]这一层指向了同一个内存地址 46 print("id(m1[‘k3‘]):%s" % id(m1[‘k3‘])) 47 print("id(m3[‘k3‘]):%s" % id(m3[‘k3‘])) 48 49 print("其他类的深拷贝".center(30, ‘*‘)) 50 print("深copy".center(30, ‘*‘)) 51 m4 = copy.deepcopy(m1) 52 print("id(m1):%s" % id(m1)) 53 print("id(m4):%s" % id(m4)) 54 # 深拷贝的m4[‘k3‘]这一层指向了不同的内存地址 55 # 深拷贝就是将除了数字和字符串以外的都重新开辟一个内存空间 56 print("id(m1[‘k3‘]):%s" % id(m1[‘k3‘])) 57 print("id(m4[‘k3‘]):%s" % id(m4[‘k3‘])) 58 59 60 # 应用:例如监控项配置的修改,要用深copy防止被copy的对象也被修改 61 print(‘浅copy会改变被拷贝对象的值‘.center(50, ‘*‘)) 62 old_dic = {‘cpu‘: [80, ], ‘disk‘: [70], ‘memory‘: [60]} 63 # 浅copy之后,更改新字典的话,新旧字典一起更改 64 new_dic = copy.copy(old_dic) 65 new_dic[‘cpu‘][0] = 50 66 print("old_dic:%s" % old_dic) 67 print("new_dic:%s" % new_dic) 68 69 print(‘深copy不会改变被拷贝对象的值‘.center(50, ‘*‘)) 70 old_dic2 = {‘cpu‘: [80, ], ‘disk‘: [70], ‘memory‘: [60]} 71 # 深copy之后,更改新字典的话,新字典的值改变而旧字典的值不会变 72 new_dic2 = copy.deepcopy(old_dic2) 73 new_dic2[‘cpu‘][0] = 50 74 print("old_dic2:%s" % old_dic2) 75 print("new_dic2:%s" % new_dic2)
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 自定义的函数 7 """ 8 9 10 # 无参数 11 def sho(): 12 print("无参数函数") 13 14 sho() 15 16 17 # 一个参数 18 # 注意:函数遇到return关键字就跳出了,所以下例中的print(‘b‘)并不会被执行 19 def show(a): 20 print(a) 21 return [11, 22] 22 print(‘b‘) 23 result = show(333) 24 print(result) 25 print("分割线".center(30, ‘*‘)) 26 27 28 # 两个参数 29 def show0(a1, a2): 30 print(a1) 31 print(a2) 32 show0(111, 333) 33 34 35 # 默认参数 36 def show1(a1, a2=555): 37 print(a1) 38 print(a2) 39 show1(111) 40 show1(111, 333) 41 show1(a2=333, a1=111) 42 43 44 # *args即代表传入的参数按照列表或元祖处理 45 # 动态参数-元祖 46 def show2(*args): 47 print(args, type(args)) 48 49 show2(11, 22, 33, 44) 50 51 52 # 动态参数-列表 53 def show2(*args): 54 print(args, type(args)) 55 56 show2([11, 22, 33, 44]) 57 l1 = [44, 55, 66, 77] 58 show2(* l1) 59 print(‘分割线-line:72‘.center(30, ‘*‘)) 60 61 62 # **kwargs代表传入的参数按照字典来处理 63 # 动态参数-字典 64 def show3(**kwargs): 65 print(kwargs, type(kwargs)) 66 67 show3(n1=11, n2=22) 68 69 70 # 动态参数-序列和字典 71 def show4(*args, **kwargs): 72 print(args, type(args)) 73 print(kwargs, type(kwargs)) 74 show4(11, 22, 33, n=44, m=55) 75 76 # 注意: 77 l = [11, 22, 33] 78 d = {‘n‘: 44, ‘m‘: 55} 79 # 直接传入会把l和d,传入*args 80 show4(l, d) 81 82 # 需要对传入的参数进行处理 83 show4(*l, **d) 84 85 86 # 用于字符串的格式化 87 str_tmp = "{0} is {1}!" 88 result = str_tmp.format(‘alex‘, ‘humor‘) 89 print(result) 90 91 result = str_tmp.format(*[‘alex‘, ‘humor‘]) 92 print(result) 93 94 str_tmp = "{name} is {actor}!" 95 print(str_tmp.format(name=‘alex‘, actor=‘humor‘)) 96 97 d_tmp = {‘name‘: ‘alex‘, ‘actor‘: ‘humor‘} 98 result = str_tmp.format(**d_tmp) 99 print(result) 100 101 102 # 简单函数lambda 103 def func_tmp(a): 104 return a+1 105 result1 = func_tmp(99) 106 print(result1) 107 result2 = lambda a: a+1 108 print(result2(99))
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 collections里常见的几个类 7 """ 8 9 # Counter 计数器 10 from collections import Counter 11 c = Counter(‘afaafsdqadsa‘) 12 print(c) 13 14 15 # OrdereDict 有序字典:记住了字典元素添加的顺序 16 from collections import OrderedDict 17 dic_tmp = OrderedDict() 18 dic_tmp[‘k1‘] = ‘v1‘ 19 dic_tmp[‘k2‘] = ‘v2‘ 20 dic_tmp[‘k3‘] = ‘v3‘ 21 print(dic_tmp) 22 print(type(dic_tmp)) 23 24 25 # defaultdict 默认字典:默认给字典的值设置一个类型 26 from collections import defaultdict 27 dic_tmp = defaultdict(list) 28 dic_tmp[‘k1‘] = ‘v1‘ 29 dic_tmp[‘k2‘] = ‘v2‘ 30 dic_tmp[‘k3‘] = ‘v3‘ 31 print(dic_tmp) 32 print(type(dic_tmp)) 33 34 35 # namedtuple 可命名元祖 36 from collections import namedtuple 37 # 例如用于定义x,y,x轴等 38 MyNamedtupleClass = namedtuple(‘MyNamedtupleClass‘, [‘x‘, ‘y‘, ‘z‘]) 39 namedtuple_tmp = MyNamedtupleClass(11, 22, 33) 40 print(namedtuple_tmp.x) 41 print(namedtuple_tmp.y) 42 print(namedtuple_tmp.z) 43 44 45 # deque 一个线程安全的双向队列:左右皆可进出 46 from collections import deque 47 deque_tmp = deque() 48 deque_tmp.append((11, 22, 33)) 49 print(deque_tmp) 50 deque_tmp.pop() 51 52 53 # queue.Queue 单向队列:先进先出 54 from queue import Queue 55 queue_tmp = Queue() 56 queue_tmp.put(11, 22, 33) 57 print(queue_tmp) 58 queue_tmp.get(11)
文件句柄 = open(‘文件路径‘, ‘打开模式‘)
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
r,只读模式(默认)。
w,只写模式。【不可读;不存在则创建;存在则删除内容;】
a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
r+,可读写文件。【可读;可写;可追加】
w+,写读
a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
rU
r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
rb
wb
ab
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 open()文件操作 7 """ 8 9 f = open(‘open_ex_test.txt‘, ‘r‘, encoding=‘utf-8‘) 10 print(f.tell()) 11 # 按照字符读 12 f.read(2) 13 # tell()返回的是根据字节得到的位置 14 print(f.tell()) 15 # seek()指定当前指针位置,seek()用的是字节 16 # 由于有中文,所以把指针指向1,就会报错,因为一个中文包括三个字节 17 # f.seek(1) 18 # print(f.read()) 19 20 # truncate():把当前指针位置之前的数据保留下来,舍去后面的(需用a+模式) 21 f.close()
为防止打开文件后忘记关闭,可以使用with来操作文件。
1 with open (‘log.txt‘, ‘r‘) as f: 2 ... 3 ...
with代码块结束后会自动关闭文件。
当然也可以同时操作多个。
1 with open (‘log1.txt‘, ‘r‘) as f1, open (‘log2.txt‘, ‘r‘) as f2: 2 pass
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "Q1mi" 4 5 """ 6 Python的内建方法 7 """ 8 9 # abs(x):返回x的绝对值 10 # all(iterable):所有元素为真,则返回真 11 result = all([1, ‘‘]) 12 print(result) 13 result = all([1, ‘a‘]) 14 print(result) 15 # any(iterable):有一个元素为真,则返回真 16 result = any((‘‘, [], )) 17 print(result) 18 result = any((‘‘, [], 1)) 19 print(result) 20 # ascii(object):返回一个可打印对象的字符串,忽略没有编码表示的字符串返回调用转义字符的repr()。 21 # As repr(), return a string containing a printable representation of an object, 22 # but escape the non-ASCII characters in the string returned by repr() using \x, \u or \U escapes. 23 # This generates a string similar to that returned by repr() in Python 2. 24 25 # bin(x): 返回x的二进制数 26 result = bin(10) 27 print(result) 28 # bool(x):返回布尔值 29 # bytearray([source[, encoding[, errors]]]):返回字节数组 30 # Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations. 31 32 # The optional source parameter can be used to initialize the array in a few different ways: 33 # 34 # If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode(). 35 # If it is an integer, the array will have that size and will be initialized with null bytes. 36 # If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array. 37 # If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array. 38 # Without an argument, an array of size 0 is created. 39 40 result = bytearray(‘周杰伦‘, encoding=‘utf-8‘) 41 print(result) 42 # bytes():返回字节 43 # 44 result = bytes(‘周杰伦‘, encoding=‘utf-8‘) 45 print(result) 46 # callable():是否可调用 47 # chr(i):返回Unicode码i代表的字符串 与ord()相反 48 print(chr(95)) 49 # ord():返回字符串对应的Unicode码 50 print(ord(‘_‘)) 51 # classmethod(function):返回类方法 52 # compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1):编译 53 # complex([real[, imag]]:复数 54 # delattr(object, name):删除属性 55 # -This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, ‘foobar‘) is equivalent to del x.foobar. 56 # dict():创建字典 57 # dir([object]):返回列表 58 # -Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. 59 # divmod(a, b):返回一个元祖(a//b, a%b) 60 # enumerate(iterable, start=0):枚举 61 # eval(expression, globals=None, locals=None):执行字符串类型的表达式,并返回结果 62 result = eval(‘99+1‘) 63 print(result) 64 # exec(object[, globals[, locals]]):执行存储在字符串或文件中的Python语句 65 result = exec("print(eval(‘99+1‘))") 66 print(result) 67 # filter(function, iterable):筛选,用前面的function去筛选后面的,留下符合条件的。 68 l1 = [11, 66, 33, 77, 22, 88, 44, 99] 69 result = filter(lambda x: x > 50, l1) 70 print(list(result)) 71 # float([x]):返回一个浮点数 72 print(float(‘+1.23‘)) 73 print(float(‘ -123456\n‘)) 74 print(float(‘1e-003‘)) 75 print(float(‘+1E6‘)) 76 print(float(‘-Infinity‘)) 77 # format(value[, format_spec]):字符串的格式化 78 # -format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] 79 # -fill ::= <any character> 80 # -align ::= "<" | ">" | "=" | "^" 81 # -sign ::= "+" | "-" | " " 82 # -width ::= integer 83 # -precision ::= integer 84 # -type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" 85 86 # frozenset([iterable]):冻结集合 87 # getattr(object, name[, default]) 88 # globals() 89 # hasattr(object, name) 90 # hash(object):返回哈希值 91 # help([object]):获取帮助信息 92 # hex(x):十六进制数 93 # id(object):返回ID 94 # input([prompt]):获取输入 95 # int():返回整数 96 print(int(‘1010‘, 2)) 97 print(int(‘1010‘, 8)) 98 print(int(‘1010‘, 10)) 99 print(int(‘1010‘, 16)) 100 # isinstance(object, classinfo):返回是不是类实例 101 # issubclass(class, classinfo):返回是不是父类 102 # iter(object[, sentinel]):返回一个迭代器 103 # len(s):返回对象的长度 104 # list([iterable]):生成列表 105 # locals():更新并返回一个本地符号表的字典 106 # map(function, iterable, ...):将函数作用于迭代器每个对象的结果返回一个迭代器 107 # max(iterable, *[,key, default]):返回最大值 108 d1 = {‘a‘: 10, ‘c‘: 5, ‘f‘: 3, ‘b‘: 7} 109 print(max(d1.items(), key=lambda t: t[1])) 110 # -max(arg1, arg2, *args[,key]) 111 # memoryview(obj):返回一个给定参数的内存视图 112 # min(iterable, *[,key, default]):返回最小值 113 # -min(arg1, arg2, *args[,key]) 114 # next(iterator[, default]) 115 # object() 116 # oct(x):八进制数 117 # open(file, mode=‘r‘, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 118 # ord() 119 # pow(x, y[, z]):x的y次幂再对z求余数 120 # print(*objects, sep=‘ ‘, end=‘\n‘, file=sys.stdout, flush=False):打印 121 # property() 122 # range(stop) 123 # -range(start, stop[, step]) 124 # repr(object) 125 # reversed(seq):反转 126 # round(number[, ndigits]):返回浮点数的四舍五入值。round(0.5)->0而round(1.5)->2 127 # set([iterable]):集合 128 # setattr(objEct,name, value):对应于getattr() 129 # slice(stop):切片 130 # -slice(start, stop[,step]):切片 131 # sorted(iterable[,key][,reverse]):排序 132 # staticmethod(function) 133 # str(object=‘‘) 134 # -str(object=b‘‘, encoding=‘utf-8‘, errors=‘strict‘) 135 # sum(iterable[, start]):求和 136 # super([type[, object-or-type]]) 137 # tuple([iterable]):元祖 138 # type(object):返回对象的类型 139 # -type(name, bases, dict):返回一个新类型的对象 140 # vars([object]):返回对象属性和属性值的字典 141 # zip(*iterables):返回一个元素来自每一个迭代器的迭代器 142 # __import__():被import声明调用的一个方法
<==the end
标签:
原文地址:http://www.cnblogs.com/liwenzhou/p/5138445.html