[关闭]
@Pigmon 2017-07-25T07:31:42.000000Z 字数 8712 阅读 874

Python 2 笔记 new

Python


文件头

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-

UTF-8声明在python 3中不需要了

下划线

以下划线开头的标识符是有特殊意义的。以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;
以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。

缩进

Python的缩进必须严格对齐,块逻辑关系依靠缩进来判断,而不是大括号

分号

每行结尾不是必须有';',但同一行多条语句之间必须有';'。

变量声明

python变量不用声明类型,根据赋值决定类型
创建时必须赋值

多变量赋值

  1. a = b = c = 1;
  2. id, age, name = 1, 28, 'John';

字符串基本操作

Python没有字符类型,一个字符也是字符串

  1. #!/usr/bin/python
  2. str = "0123456";
  3. print str[1]; # 输出 1
  4. print str[0:3]; # 输出 012 [include:exclude]
  5. print str[4:]; # 输出 456
  6. print str * 2; # 输出 01234560123456,就是连2次
  7. print str + " OK."; # 输出 0123456 OK.
  8. print len(str); # 7

补充的字符串操作

  1. str = "This is Sparda!";
  2. is_in = ("is" in str); # True
  3. not_in = ("is" not in str); # False
  4. # 格式化输出 FORMAT % (param1, param2...)
  5. str2 = "My name is %s and I am %d years old." % ("John", 28);
  6. str3 = "%04x" % (15); # 000f
  7. str4 = "%6.4f" % (12.16); # 12.1600 也可以 "%.4f"
  8. # 三引号长字符串,web开发中可以从双引号的泥沼中解脱了
  9. str5 = '''This is a
  10. long string can cross line.
  11. if there are troubles
  12. like %s or " dont worry, it
  13. will be OK, sweet!
  14. No, not \\n, \nit will cause a line break, even here.''';
  15. # unicode
  16. str6 = u'Hello\u0020Python.'; # Hello Python

一些觉得会比较常用的字符串内建方法

  1. str = "This is Sparda!";
  2. # substr出现的次数
  3. # @param2: 起始位置
  4. # @param3: 结束位置,可选,默认结尾
  5. # @return: 出现次数
  6. cnter1 = str.count("is", 0); # 2,This里最后2个字母也被统计了
  7. cnter2 = str.count("is", 4, 15); # 1,从第4个位置开始,所以只有1个is出现过
  8. # 编码解码
  9. # @param1: 格式字符串,可选。默认'UTF-8'
  10. # @param2: 错误的处理方案,可选,默认 'strict'
  11. # @return: 编码解码后的结果字符串
  12. encoded = str.encode('base64');
  13. decoded = encoded.decode('base64');
  14. # 判断字符串是否以x开始\结尾
  15. # @param1: 待判断的头\尾字符串
  16. # @param2: 起始位置,可选,默认0
  17. # @param3: 结束位置,默认结尾
  18. # @return: True/False
  19. is_endwidth = str.endswith("!"); # True
  20. is_startwidth = str.startswith("Wow"); # False
  21. # 查找子串
  22. # @param2: 起始位置,可选,默认0
  23. # @param3: 结束位置,默认结尾
  24. # @return: 第一次出现位置,找不到返回-1
  25. idx = str.find("is"); # 2
  26. idx = str.rfind("is"); # 5 从右边开始查找
  27. # 一些判断函数
  28. string.isdigit(); # 是否全由数字组成
  29. string.isalpha(); # 是否全由字母组成
  30. string.isalnum(); # 至少有一个字符,且只由字符或数字组成
  31. # 替换子串
  32. # @param1: Old
  33. # @param2: New
  34. replaced = str.replace("Sparda", "Party"); # This is Party!
  35. # 分割
  36. # @param1: 分隔符,默认空格
  37. # @param2: 分割次数,可选
  38. # @return: 分割后的数组
  39. splided1 = str.split(); # ['This', 'is', 'Sparda!']
  40. splided2 = str.split(' is '); # ['This', 'Sparda!']

List

  1. #!/usr/bin/python
  2. list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
  3. tinylist = [123, 'john']
  4. print list # 输出完整列表 - ['abcd', 786, 2.23, 'john', 70.2]
  5. print list[0] # 输出列表的第一个元素 - abcd
  6. print list[1:3] # 输出第二个至第三个的元素 - [786, 2.23]
  7. print list[2:] # 输出从第三个开始至列表末尾的所有元素 - [2.23, 'john', 70.2]
  8. print tinylist[-2]; # 123
  9. print tinylist * 2 # 输出列表两次
  10. print len(list); # 5
  11. print list + tinylist # 打印组合的列表
  12. print 123 in tinylist; # True
  13. print 123 not in tinylist; # False
  14. del tinylist[1]; # list = [123]; 删除list元素
  15. for x in [1, 2, 3]: print x # 基本循环方式
  16. # 刚看到的用法
  17. tup = (1, 2, 3);
  18. lst = [x**2 for x in tup]; # [1, 4, 9]

补充的list相关函数

  1. #!/usr/bin/python
  2. list1 = [9, 2, 8];
  3. tuple1 = ('Tom', 'ClassA', 29);
  4. print max(list1); # 9
  5. print min(list1); # 2
  6. print len(list1); # 3
  7. print list(tuple1); # ['Tom', 'ClassA', 29]

list的部分内建方法

  1. list1 = [9, 2, 8];
  2. list1.append(6); # [9, 2, 8, 6]
  3. # x在list中出现的次数
  4. list1.count(8); # 1
  5. # 在list后面追加一个序列
  6. list1.extend([0, 3]); # [9, 2, 8, 6, 0, 3]
  7. # x在list中第一次出现的index
  8. list1.index(2); # 1
  9. # 在x位置插入元素y
  10. list1.insert(1, 7); # [9, 7, 2, 8, 6, 0, 3]
  11. # 删除最后一个元素并返回其值
  12. list1.pop(); # 3
  13. # 删除list中的元素x
  14. list1.remove(0); # [9, 7, 2, 8, 6]
  15. # 反转list中所有元素
  16. list1.reverse(); # [6, 8, 2, 7, 9]
  17. # 排序
  18. list1.sort(); # [2, 6, 7, 8, 9]
  19. # 自定义排序函数
  20. def my_sorter(a, b):
  21. if (a > b):
  22. return -1;
  23. elif (a < b):
  24. return 1;
  25. else:
  26. return 0;
  27. list1.sort(my_sorter); # [9, 8, 7, 6, 2]

Tuple(元组)

Tuple是只读的List,方括号变成小括号包围
不能用下标修改或删除Tuple中的元素
只有一个元素的Tuple需要一个逗号:

  1. tup1 = (123,);

其他都和List一样

任意用逗号分隔的几个元素被Python默认为Tuple

  1. a, b, c = 1, 2, 3

Dictionary

就是PHP的array
冒号,逗号
{Key : Value, Key : Value...}
Key必须是基本不可变类型,如数字,字符串,Tuple
Key之间类型不必相同
Value可以是任意类型,Value之间类型不必相同

  1. #!/usr/bin/python
  2. dict1 = {};
  3. dict1["One"] = 1;
  4. dict1[2] = "Two";
  5. print dict1; # 输出: {2: 'Two', 'One': 1}
  6. print len(dict1); # 2
  7. del dict1[2]; # {'One':1}
  8. dict2 = {"ID" : 101, "Name" : "John", "Age" : 28};
  9. dict2["Age"] = 29; # {'Age': 29, 'ID': 101, 'Name': 'John'}

觉得会比较常用的Dictionary内建方法

  1. #!/usr/bin/python
  2. dict1 = {'ID':123, 'Name':'John', 'Age':28};
  3. print dict1.keys(); # ['Age', 'ID', 'Name']
  4. print dict1.values(); # [28, 123, 'John']
  5. print dict1.items(); # [('Age', 28), ('ID', 123), ('Name', 'John')]
  6. print dict1.has_key('ID'); # True
  7. dict1.clear(); # {}
  8. seq = ('ID', 'Name', 'Age');
  9. dict2 = dict.fromkeys(seq, 'n/a'); # {'Age': 'n/a', 'ID': 'n/a', 'Name': 'n/a'}

常用类型转换

  1. str1 = "12";
  2. int_num = int(str1);
  3. float_num = float(str1);
  4. str2 = str(int_num);
  5. str3 = unicode(int_num);
  6. hex_num = hex(int_num);

Python比较独特的运算符

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. # **和//是其他语言没见过的,相应的还有'**='和'//='
  4. a = 5;
  5. b = a ** 2; # 乘方
  6. c = b // 10; # 除后取整
  7. print b; # 5^2 = 25
  8. print c; # 25 除 10 = 2.5 取整 输出 : 2
  9. # Python中逻辑与或非运算符和其他语言不同
  10. # 直接使用英文的 and, or, not
  11. if (not ((b <= c or c != 0) and a == 0)):
  12. print "Check!"; # 输出 Check!
  13. else:
  14. print "Wrong...";
  15. # in, not in
  16. tinylist = [123, 'john'];
  17. if (123 in tinylist): print "Check!";
  18. if (234 not in tinylist): print "Check 2!";
  19. # is, is not
  20. # 是判断两个标识符是不是引用自一个对象 if (id(x) == id(y))
  21. if (a is b) : print "a and b has a same id";

条件语句

Python 不支持 switch-case
if,elif,else条件语句后面要跟 ':'

  1. a = 6;
  2. if a <= 3:
  3. print "1st Class.";
  4. elif a <= 6:
  5. print "Middle Class"; # got here.
  6. else:
  7. print "Dame it!";

循环

循环和if一样,主体语句最后有冒号。
循环可以跟else块,循环结束后会执行else里的内容(能想到唯一的用处就是看起来清楚些,因为Python是靠缩进来分块的)

  1. #!/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. a = 6;
  4. counter = 0;
  5. while (counter < 12):
  6. a += 2;
  7. counter += 1;
  8. else:
  9. print a; # 30
  10. for chara in "ABC":
  11. print chara;
  12. arr = [1, 2, 3];
  13. for number in arr:
  14. print number;
  15. for idx in range(len(arr)):
  16. print arr[idx];
  17. else:
  18. print "Done.";

常用运算函数

  1. #!/usr/bin/python
  2. import math
  3. # -*- coding: UTF-8 -*-
  4. # 数学计算
  5. print abs(-3.14); # 3.14
  6. print math.ceil(3.2); # 4.0 大于x的最小整数
  7. print math.floor(3.2); # 3.0 小于x的最大整数
  8. print cmp(1, 2); # -1 x<y->-1, x>y->1, x==y->0
  9. print math.exp(1); # 2.718... e^x
  10. print math.fabs(-10); # 10.0
  11. print math.log(math.e); # 1.0 自然对数ln
  12. print math.log10(100); # 2.0 以10为底对数
  13. print max(1, 5, 2); # 5
  14. print min(1, 5, 2); # 1
  15. print math.modf(3.14); # (0.14, 3.0) 将x的小数部分与整数部分存入一个Tuple
  16. print pow(2, 3); # 8 x^y
  17. print round(3.6); # 4.0 四舍五入
  18. print math.sqrt(25); # 5.0 开方
  19. # 随机数
  20. arr = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
  21. print random.choice(arr); # 随机从arr中取一个值
  22. print random.choice(range(5)); # 随机从1-4取值
  23. print random.random(); # 随机生成0-1之间浮点数
  24. random.shuffle(arr); print arr; # 打乱arr的顺序
  25. print random.uniform(12, 18); # 随机生成[x, y)或[x, y]内的数,是否闭区间取决于取整
  26. # 三角函数
  27. arc_val = math.pi / 6.0;
  28. print math.sin(arc_val); # 0.5 输入为弧度值,其他cos,tan, asin, acos, atan等
  29. print math.hypot(3, 4); # 5.0 sqrt(x^2 + y^2)
  30. print math.degrees(arc_val); # 30.0 弧度转角度
  31. print math.radians(90); # 1.57... 角度转弧度,这里输出的是0.5 * PI

日期时间

  1. #!/usr/bin/python
  2. import time;
  3. time.time(); # 浮点的UNIX时间戳
  4. localtime = time.localtime(time.time());
  5. print localtime;
  6. #time.struct_time(tm_year=2016, tm_mon=2, tm_mday=24, tm_hour=2, tm_min=31, tm_sec=11, tm_wday=2, tm_yday=55, tm_isdst=0)
  7. print localtime[0]; # 2016
  8. beauty_time = time.asctime(time.localtime(time.time())); # Wed Feb 24 02:33:26 2016
  9. # time.clock()用于精确的统计时间
  10. print time.clock();
  11. time.sleep(3.1415926);
  12. print time.clock();
  13. # 格式化输出
  14. print time.strftime("%a %Y/%m/%d %H:%M:%S", time.gmtime()); # Tue 2016/02/23 18:48:16

函数

Python中所有的传入参数都是按引用传递的
函数的基本格式:

  1. def func_name (param1, param2,...):
  2. "第一行居然可以写个函数说明,注释有咩不好吗?"
  3. something;
  4. return something;

命名参数,不强制

  1. #!/usr/bin/python
  2. def foo (num1, num2):
  3. return num1 + num2;
  4. print foo(1, 2); # 3
  5. print foo(num1 = 2, num2 = 6); # 8

缺省参数,和其他语言一样,可以多个,必须都在后面

  1. #!/usr/bin/python
  2. def foo(num, times = 2):
  3. return num * times;
  4. print foo(3); # 6
  5. print foo(2, 4); # 8

不定长参数。这么多年我就用过一次这东西

  1. #!/usr/bin/python
  2. def foo(num, *vartuple):
  3. ret = num;
  4. for var in vartuple:
  5. ret += var;
  6. return ret;
  7. print foo(1, 1, 1, 1, 1); # 5

Lambda,类似于C用宏定义小函数,只能有一个语句,限制较多,不知道什么地方可用到

  1. #!/usr/bin/python
  2. bigger = lambda a,b:a>b;
  3. print bigger(1, 2); # False

  1. #!/usr/bin/python
  2. import math
  3. # 类名后面有 ':'
  4. class Coord3:
  5. "这里第一行也可以写说明"
  6. # 构造函数,固定名字,还必须传入一个self,无聊
  7. def __init__ (self, _x, _y, _z):
  8. self.x, self.y, self.z = _x, _y, _z;
  9. self.__list = [_x, _y, _z];
  10. # 析构函数,固定名字,必须传一个self
  11. def __del__ (self):
  12. del self.__list;
  13. # 一个普通的成员方法,依旧必须传self
  14. def print_me (self):
  15. print "(%d, %d, %d)" % (self.x, self.y, self.z);
  16. # 运算符重载,包括但不限于:
  17. # __add__ +
  18. # __sub__ -
  19. # __len__ len(x)
  20. # __cmp__ >, <, ==, !=, >=, <= etc.
  21. def __add__ (self, other):
  22. return Coord3(self.x + other.x, self.y + other.y, self.z + other.z);
  23. # 静态方法声明,还有个类方法,我之前一直以为这俩是一个东西...
  24. @staticmethod
  25. def distance (_pt1, _pt2): # 怎么限制输入类型呢?
  26. return math.sqrt((_pt1.x - _pt2.x)**2 + (_pt1.y - _pt2.y)**2 + (_pt1.z - _pt2.z)**2);
  27. # 类的继承,关键字是(),多继承可以,中间用','分隔
  28. class Coord2(Coord3):
  29. __list = [0, 0];
  30. def __init__ (self, _x, _y):
  31. # 调用父类构造方法
  32. Coord3.__init__ (self, _x, _y, 0);
  33. self.__list = [_x, _y]; # 这里若不赋值还当它不存在,析构时会报错
  34. def __del__(self):
  35. del self.__list;
  36. def print_me(self):
  37. print "(%d, %d)" % (self.x, self.y);
  38. # 实例化的方法:直接 类名(Params)
  39. pt1 = Coord3(1, 1, 1);
  40. pt2 = Coord3(0, 0, 0);
  41. pt3 = pt1 + pt2; # 这是重载的'+'
  42. pt3.print_me(); # (1, 1, 1)

基本文件操作

  1. #!/usr/bin/python
  2. import os
  3. fo = open("test.txt", "r");
  4. print fo.name;
  5. print fo.mode; # r
  6. #fo.write("I am writing.\nAnd writing.");
  7. content = fo.read();# @param1: 读取的Byte
  8. print fo.tell(); # 当前指针位置
  9. # seek: @Param1:offset @Param2: 默认0-从开头算,1-从当前位置算,2-从文件末尾算
  10. fo.seek(0, 0); # 到开头
  11. line1 = fo.readline();
  12. fo.close();
  13. print fo.closed; # True

其他操作
OS包里封装了很多Linux的目录和文件操作,具体用的时候查文档

  1. #!/usr/bin/python
  2. import os
  3. os.rename('test.txt', 'log.txt');
  4. os.remove("test2.txt");
  5. os.mkdir("test");
  6. os.rmdir('test');
  7. os.chdir("test"); # 转到目录
  8. os.getcwd(); # 输出当前路径

推导式

  1. list1 = ['apple', 'banana', 'orange']
  2. dict1 = {key: value for key,value in enumerate(list1) if len(value)>5}
  3. # dict1 = {1: 'banana', 2: 'orange'}
  4. # 后面的if不是必须的
  5. # tuple和list如果不用enumerate转换没有key:value结构,会报错

yield

在生成器函数中的中断返回,因为在Unity中经常用yield,所以不多写说明了。

  1. def foo(num):
  2. for i in range(num):
  3. yield i * 2
  4. # 0, 2, 4, 6, 8
  5. for val in foo(5):
  6. print val

partial

给多个参数的函数加默认参数的方式

  1. def add(a, b):
  2. return a + b
  3. add_88 = partial(add, 88)
  4. print add_88(800) # 888

有默认参数的情况,也没什么变化

  1. def add2(a, b, c=800):
  2. return a + b + c
  3. add_80 = partial(add2, 80)
  4. print add_80(8) # 888
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注