@Pigmon
2017-07-25T07:31:42.000000Z
字数 8712
阅读 1218
Python
#!/usr/bin/python# -*- coding: UTF-8 -*-
UTF-8声明在python 3中不需要了
以下划线开头的标识符是有特殊意义的。以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;
以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。
Python的缩进必须严格对齐,块逻辑关系依靠缩进来判断,而不是大括号
每行结尾不是必须有';',但同一行多条语句之间必须有';'。
python变量不用声明类型,根据赋值决定类型
创建时必须赋值
a = b = c = 1;id, age, name = 1, 28, 'John';
Python没有字符类型,一个字符也是字符串
#!/usr/bin/pythonstr = "0123456";print str[1]; # 输出 1print str[0:3]; # 输出 012 [include:exclude]print str[4:]; # 输出 456print str * 2; # 输出 01234560123456,就是连2次print str + " OK."; # 输出 0123456 OK.print len(str); # 7
补充的字符串操作
str = "This is Sparda!";is_in = ("is" in str); # Truenot_in = ("is" not in str); # False# 格式化输出 FORMAT % (param1, param2...)str2 = "My name is %s and I am %d years old." % ("John", 28);str3 = "%04x" % (15); # 000fstr4 = "%6.4f" % (12.16); # 12.1600 也可以 "%.4f"# 三引号长字符串,web开发中可以从双引号的泥沼中解脱了str5 = '''This is along string can cross line.if there are troubleslike %s or " dont worry, itwill be OK, sweet!No, not \\n, \nit will cause a line break, even here.''';# unicodestr6 = u'Hello\u0020Python.'; # Hello Python
一些觉得会比较常用的字符串内建方法
str = "This is Sparda!";# substr出现的次数# @param2: 起始位置# @param3: 结束位置,可选,默认结尾# @return: 出现次数cnter1 = str.count("is", 0); # 2,This里最后2个字母也被统计了cnter2 = str.count("is", 4, 15); # 1,从第4个位置开始,所以只有1个is出现过# 编码解码# @param1: 格式字符串,可选。默认'UTF-8'# @param2: 错误的处理方案,可选,默认 'strict'# @return: 编码解码后的结果字符串encoded = str.encode('base64');decoded = encoded.decode('base64');# 判断字符串是否以x开始\结尾# @param1: 待判断的头\尾字符串# @param2: 起始位置,可选,默认0# @param3: 结束位置,默认结尾# @return: True/Falseis_endwidth = str.endswith("!"); # Trueis_startwidth = str.startswith("Wow"); # False# 查找子串# @param2: 起始位置,可选,默认0# @param3: 结束位置,默认结尾# @return: 第一次出现位置,找不到返回-1idx = str.find("is"); # 2idx = str.rfind("is"); # 5 从右边开始查找# 一些判断函数string.isdigit(); # 是否全由数字组成string.isalpha(); # 是否全由字母组成string.isalnum(); # 至少有一个字符,且只由字符或数字组成# 替换子串# @param1: Old# @param2: Newreplaced = str.replace("Sparda", "Party"); # This is Party!# 分割# @param1: 分隔符,默认空格# @param2: 分割次数,可选# @return: 分割后的数组splided1 = str.split(); # ['This', 'is', 'Sparda!']splided2 = str.split(' is '); # ['This', 'Sparda!']
#!/usr/bin/pythonlist = [ 'abcd', 786 , 2.23, 'john', 70.2 ]tinylist = [123, 'john']print list # 输出完整列表 - ['abcd', 786, 2.23, 'john', 70.2]print list[0] # 输出列表的第一个元素 - abcdprint list[1:3] # 输出第二个至第三个的元素 - [786, 2.23]print list[2:] # 输出从第三个开始至列表末尾的所有元素 - [2.23, 'john', 70.2]print tinylist[-2]; # 123print tinylist * 2 # 输出列表两次print len(list); # 5print list + tinylist # 打印组合的列表print 123 in tinylist; # Trueprint 123 not in tinylist; # Falsedel tinylist[1]; # list = [123]; 删除list元素for x in [1, 2, 3]: print x # 基本循环方式# 刚看到的用法tup = (1, 2, 3);lst = [x**2 for x in tup]; # [1, 4, 9]
补充的list相关函数
#!/usr/bin/pythonlist1 = [9, 2, 8];tuple1 = ('Tom', 'ClassA', 29);print max(list1); # 9print min(list1); # 2print len(list1); # 3print list(tuple1); # ['Tom', 'ClassA', 29]
list的部分内建方法
list1 = [9, 2, 8];list1.append(6); # [9, 2, 8, 6]# x在list中出现的次数list1.count(8); # 1# 在list后面追加一个序列list1.extend([0, 3]); # [9, 2, 8, 6, 0, 3]# x在list中第一次出现的indexlist1.index(2); # 1# 在x位置插入元素ylist1.insert(1, 7); # [9, 7, 2, 8, 6, 0, 3]# 删除最后一个元素并返回其值list1.pop(); # 3# 删除list中的元素xlist1.remove(0); # [9, 7, 2, 8, 6]# 反转list中所有元素list1.reverse(); # [6, 8, 2, 7, 9]# 排序list1.sort(); # [2, 6, 7, 8, 9]# 自定义排序函数def my_sorter(a, b):if (a > b):return -1;elif (a < b):return 1;else:return 0;list1.sort(my_sorter); # [9, 8, 7, 6, 2]
Tuple是只读的List,方括号变成小括号包围
不能用下标修改或删除Tuple中的元素
只有一个元素的Tuple需要一个逗号:
tup1 = (123,);
其他都和List一样
任意用逗号分隔的几个元素被Python默认为Tuple
a, b, c = 1, 2, 3
就是PHP的array
冒号,逗号
{Key : Value, Key : Value...}
Key必须是基本不可变类型,如数字,字符串,Tuple
Key之间类型不必相同
Value可以是任意类型,Value之间类型不必相同
#!/usr/bin/pythondict1 = {};dict1["One"] = 1;dict1[2] = "Two";print dict1; # 输出: {2: 'Two', 'One': 1}print len(dict1); # 2del dict1[2]; # {'One':1}dict2 = {"ID" : 101, "Name" : "John", "Age" : 28};dict2["Age"] = 29; # {'Age': 29, 'ID': 101, 'Name': 'John'}
觉得会比较常用的Dictionary内建方法
#!/usr/bin/pythondict1 = {'ID':123, 'Name':'John', 'Age':28};print dict1.keys(); # ['Age', 'ID', 'Name']print dict1.values(); # [28, 123, 'John']print dict1.items(); # [('Age', 28), ('ID', 123), ('Name', 'John')]print dict1.has_key('ID'); # Truedict1.clear(); # {}seq = ('ID', 'Name', 'Age');dict2 = dict.fromkeys(seq, 'n/a'); # {'Age': 'n/a', 'ID': 'n/a', 'Name': 'n/a'}
str1 = "12";int_num = int(str1);float_num = float(str1);str2 = str(int_num);str3 = unicode(int_num);hex_num = hex(int_num);
#!/usr/bin/python# -*- coding: UTF-8 -*-# **和//是其他语言没见过的,相应的还有'**='和'//='a = 5;b = a ** 2; # 乘方c = b // 10; # 除后取整print b; # 5^2 = 25print c; # 25 除 10 = 2.5 取整 输出 : 2# Python中逻辑与或非运算符和其他语言不同# 直接使用英文的 and, or, notif (not ((b <= c or c != 0) and a == 0)):print "Check!"; # 输出 Check!else:print "Wrong...";# in, not intinylist = [123, 'john'];if (123 in tinylist): print "Check!";if (234 not in tinylist): print "Check 2!";# is, is not# 是判断两个标识符是不是引用自一个对象 if (id(x) == id(y))if (a is b) : print "a and b has a same id";
Python 不支持 switch-case
if,elif,else条件语句后面要跟 ':'
a = 6;if a <= 3:print "1st Class.";elif a <= 6:print "Middle Class"; # got here.else:print "Dame it!";
循环和if一样,主体语句最后有冒号。
循环可以跟else块,循环结束后会执行else里的内容(能想到唯一的用处就是看起来清楚些,因为Python是靠缩进来分块的)
#!/usr/bin/python# -*- coding: UTF-8 -*-a = 6;counter = 0;while (counter < 12):a += 2;counter += 1;else:print a; # 30for chara in "ABC":print chara;arr = [1, 2, 3];for number in arr:print number;for idx in range(len(arr)):print arr[idx];else:print "Done.";
#!/usr/bin/pythonimport math# -*- coding: UTF-8 -*-# 数学计算print abs(-3.14); # 3.14print math.ceil(3.2); # 4.0 大于x的最小整数print math.floor(3.2); # 3.0 小于x的最大整数print cmp(1, 2); # -1 x<y->-1, x>y->1, x==y->0print math.exp(1); # 2.718... e^xprint math.fabs(-10); # 10.0print math.log(math.e); # 1.0 自然对数lnprint math.log10(100); # 2.0 以10为底对数print max(1, 5, 2); # 5print min(1, 5, 2); # 1print math.modf(3.14); # (0.14, 3.0) 将x的小数部分与整数部分存入一个Tupleprint pow(2, 3); # 8 x^yprint round(3.6); # 4.0 四舍五入print math.sqrt(25); # 5.0 开方# 随机数arr = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20];print random.choice(arr); # 随机从arr中取一个值print random.choice(range(5)); # 随机从1-4取值print random.random(); # 随机生成0-1之间浮点数random.shuffle(arr); print arr; # 打乱arr的顺序print random.uniform(12, 18); # 随机生成[x, y)或[x, y]内的数,是否闭区间取决于取整# 三角函数arc_val = math.pi / 6.0;print math.sin(arc_val); # 0.5 输入为弧度值,其他cos,tan, asin, acos, atan等print math.hypot(3, 4); # 5.0 sqrt(x^2 + y^2)print math.degrees(arc_val); # 30.0 弧度转角度print math.radians(90); # 1.57... 角度转弧度,这里输出的是0.5 * PI
#!/usr/bin/pythonimport time;time.time(); # 浮点的UNIX时间戳localtime = time.localtime(time.time());print localtime;#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)print localtime[0]; # 2016beauty_time = time.asctime(time.localtime(time.time())); # Wed Feb 24 02:33:26 2016# time.clock()用于精确的统计时间print time.clock();time.sleep(3.1415926);print time.clock();# 格式化输出print time.strftime("%a %Y/%m/%d %H:%M:%S", time.gmtime()); # Tue 2016/02/23 18:48:16
Python中所有的传入参数都是按引用传递的
函数的基本格式:
def func_name (param1, param2,...):"第一行居然可以写个函数说明,注释有咩不好吗?"something;return something;
命名参数,不强制
#!/usr/bin/pythondef foo (num1, num2):return num1 + num2;print foo(1, 2); # 3print foo(num1 = 2, num2 = 6); # 8
缺省参数,和其他语言一样,可以多个,必须都在后面
#!/usr/bin/pythondef foo(num, times = 2):return num * times;print foo(3); # 6print foo(2, 4); # 8
不定长参数。这么多年我就用过一次这东西
#!/usr/bin/pythondef foo(num, *vartuple):ret = num;for var in vartuple:ret += var;return ret;print foo(1, 1, 1, 1, 1); # 5
Lambda,类似于C用宏定义小函数,只能有一个语句,限制较多,不知道什么地方可用到
#!/usr/bin/pythonbigger = lambda a,b:a>b;print bigger(1, 2); # False
#!/usr/bin/pythonimport math# 类名后面有 ':'class Coord3:"这里第一行也可以写说明"# 构造函数,固定名字,还必须传入一个self,无聊def __init__ (self, _x, _y, _z):self.x, self.y, self.z = _x, _y, _z;self.__list = [_x, _y, _z];# 析构函数,固定名字,必须传一个selfdef __del__ (self):del self.__list;# 一个普通的成员方法,依旧必须传selfdef print_me (self):print "(%d, %d, %d)" % (self.x, self.y, self.z);# 运算符重载,包括但不限于:# __add__ +# __sub__ -# __len__ len(x)# __cmp__ >, <, ==, !=, >=, <= etc.def __add__ (self, other):return Coord3(self.x + other.x, self.y + other.y, self.z + other.z);# 静态方法声明,还有个类方法,我之前一直以为这俩是一个东西...@staticmethoddef distance (_pt1, _pt2): # 怎么限制输入类型呢?return math.sqrt((_pt1.x - _pt2.x)**2 + (_pt1.y - _pt2.y)**2 + (_pt1.z - _pt2.z)**2);# 类的继承,关键字是(),多继承可以,中间用','分隔class Coord2(Coord3):__list = [0, 0];def __init__ (self, _x, _y):# 调用父类构造方法Coord3.__init__ (self, _x, _y, 0);self.__list = [_x, _y]; # 这里若不赋值还当它不存在,析构时会报错def __del__(self):del self.__list;def print_me(self):print "(%d, %d)" % (self.x, self.y);# 实例化的方法:直接 类名(Params)pt1 = Coord3(1, 1, 1);pt2 = Coord3(0, 0, 0);pt3 = pt1 + pt2; # 这是重载的'+'pt3.print_me(); # (1, 1, 1)
#!/usr/bin/pythonimport osfo = open("test.txt", "r");print fo.name;print fo.mode; # r#fo.write("I am writing.\nAnd writing.");content = fo.read();# @param1: 读取的Byte数print fo.tell(); # 当前指针位置# seek: @Param1:offset @Param2: 默认0-从开头算,1-从当前位置算,2-从文件末尾算fo.seek(0, 0); # 到开头line1 = fo.readline();fo.close();print fo.closed; # True
其他操作
OS包里封装了很多Linux的目录和文件操作,具体用的时候查文档
#!/usr/bin/pythonimport osos.rename('test.txt', 'log.txt');os.remove("test2.txt");os.mkdir("test");os.rmdir('test');os.chdir("test"); # 转到目录os.getcwd(); # 输出当前路径
list1 = ['apple', 'banana', 'orange']dict1 = {key: value for key,value in enumerate(list1) if len(value)>5}# dict1 = {1: 'banana', 2: 'orange'}# 后面的if不是必须的# tuple和list如果不用enumerate转换没有key:value结构,会报错
在生成器函数中的中断返回,因为在Unity中经常用yield,所以不多写说明了。
def foo(num):for i in range(num):yield i * 2# 0, 2, 4, 6, 8for val in foo(5):print val
给多个参数的函数加默认参数的方式
def add(a, b):return a + badd_88 = partial(add, 88)print add_88(800) # 888
有默认参数的情况,也没什么变化
def add2(a, b, c=800):return a + b + cadd_80 = partial(add2, 80)print add_80(8) # 888