ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[toc] # 基础特性 ```python # Python语句中一般以新行作为为语句的结束符。多行显示要通过 \ num1 = 1 num2 = 2 num3 = 3 total = num1 + \ num2 + \ num3 print("total is : %d"%total) # 输入输出 name = input('please enter your name:'); print('hello,',name); # 刷新荧幕,实时输出 import time import sys for i in range(5): print(i, end=' '), sys.stdout.flush() # 加这句就能每秒输出 time.sleep(1) # 在Python里常量是可以改变的 PI = 3.14; PI = 3.14159; # 删除变量 del d ``` ## 运算符 ### 运算符优先级 ``` #运算优先级由低到高 Lambda 逻辑运算符: or 逻辑运算符: and 逻辑运算符:not 成员测试: in, not in 同一性测试: is, is not 比较: <,<=,>,>=,!=,== 按位或: | 按位异或: ^ 按位与: & 移位: << ,>> 加法与减法: + ,- 乘法、除法与取余: *, / ,% 正负号: +x,-x ``` ### 短路运算符 ```python a=1 b=2 c1 = a and b # 前面为false就一定为false,不必执行第二个 c2 = a or b # 前面为true就一定为true,不必执行第二个 print(c1,c2) ``` ### 三目运算符(三元表达式) > Python不支持三目运算符,不过有以下相对应的支持 ```python # x if condition else y # 为真时的结果 if 判断条件 else 为假时的结果(注意,没有冒号) # 斐波那契数列 def fn(n): return n if n < 2 else fn(n-1)+fn(n-2) # np.where(判断条件,为真时的处理,为假时的处理) # np为numpy对象 pip install --upgrade numpy # x = np.where(x%2==1, x+1, x) import numpy as np x = 0 x = np.where(x%2==1, x+1, x) ``` ## 字符串 ```python # 字符串占位符替换,如果字符串里面有%,就要用%%来表示 # %2d,不足2位,前面补空格;%02d,不足2位,前面补0; # 其他的还有%s,%f,%r str = '%2d-%02d' % (3, 1) print(str) print('%.2f' % 3.1415926) # %r text = "I am %d years old." % 22 print("I said: %s." % text) # I said: I am 22 years old.. %s用str()方法处理对象 print("I said: %r." % text) # I said: 'I am 22 years old.'. %r用rper()方法处理对象 import datetime d = datetime.date.today() print("%s" % d) # 2018-06-12 print("%r" % d) # datetime.date(2018, 6, 12) %r打印时能够重现它所代表的对象 # 转义与不转义 print('\\\t\\'); print(r'\\\t\\'); # r''表示''内部的字符串默认不转义 # ''' : 多行字符串 str = '''line1 line2 \\ line3 '''; print(str); # r: 非转义的原始字符串 str = r'''line1 we \\ line2 line3 '''; print(str); # u: 表示unicode字符串,后面字符串以 Unicode 格式 进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱码。在python3中可以忽略 str = u"我是含有中文字符组成的字符串。" # b: bytes Python3里默认的str是(Python2里的)unicode, bytes是(Python2)的str, b前缀代表的就是bytes。 Python2里, b前缀没什么具体意义, 只是为了兼容Python3的这种写法。 # 字符串repeat 'str1'*10 # str1str1str1str1str1str1str1str1str1str1 # format 格式化函数 "{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 "{0} {1}".format("hello", "world") # 设置指定位置 "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world' print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com")) site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site)) ``` ## 条件判断 在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。 在命令if not 1中,1便会转换为bool类型的True。not是逻辑运算符非,not 1则恒为False。因此if语句if not 1之下的语句,永远不会执行。 ```python # 判断 没有===,用is代替=== 1 == '1' # False age = 19 if age > 30: print('中') elif age > 18: print('成') else: print('小') birth = input('birth: ') birth = int(birth) # str不能直接和整数比较,必须先把str转换成整数。 if birth < 2000: print('00前') else: print('00后') ``` ## 循环 ```python sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: if(x == 5): continue if(x == 10): break sum = sum + x # 4950 list = list(range(100)) # [0, 1, 2, 3, 4] res = 0; for item in list: res += item # 4950 res = 0 while len(list) > 0: res += list[-1] list.pop() ``` ## 字典 (dicts) ```python dicts = {'name': 'zxg' , 'sex': 'boy', 'age' : 18} dict.pop('name'); # 删除 dicts.get('name','default_value') d = dict([('a', 1), ('b', 2), ('c', 3)]) d # {'a': 1, 'b': 2, 'c': 3} # dict方法 ``` ## list和tuple ```python s = ['python', 'java', ['asp', 'php'], 'scheme'] # list,list是有顺序的,可以用来模拟队列的FIFO特性 t = ('a', 'b', ['A', 'B']) # 成员不可变,但成员里面的长度可以变 t = (1,) # 因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple list.append('Google') del list['Google'] # http://www.runoob.com/python/python-lists.html ``` ## 集合(set) > 没有value的dicts 无序集合,无重复 ```python s = set([1, 1, 2, 2, 3, 3]) # {1, 2, 3} s.add(31) s.remove(1) s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) s3 = s1 & s2 # 交集 {2, 3} s4 = s1 | s2 # 并集 {1, 2, 3, 4} a = ['c', 'b', 'a'] a.sort() a # ['a', 'b', 'c'] a = 'abc' a.replace('a', 'A') # 'Abc' a # 'abc' ``` ## 数据类型判断 > python是一切皆对象,判断数据类型就是判断其是否属于某一个对象 ### type ```python type(123) # <class 'int'> type('str') # <class 'str'> type(None) # <type(None) 'NoneType'> type(123)==type(456) # True type('abc')==type(123) # false type(Object) # <class 'type'> 自定义类(元类生成的) ``` ### isinstance ```python x = 2 s = 'ww' isinstance(x, (int, float)) # True isinstance(s, (int, float)) # False ``` ### callable 判断一个对象是否能被直接调用 ```python callable(Student()) # True callable(max) # True callable('str') ``` ## 深拷贝和浅拷贝 ```python # 直接赋值,传递对象的引用而已,原始列表改变,被赋值的b也会做相同的改变 alist=[1,2,3,["a","b"]] b=alist alist.append(5) print(b) # [1, 2, 3, ['a', 'b'], 5] # copy浅拷贝,没有拷贝子对象,所以原始数据改变,子对象会改变 import copy c=copy.copy(alist) alist.append(5) print(c) # [1, 2, 3, ['a', 'b']] 最外层子对象没有改变,因为此处不同于引用复制,而是浅拷贝 alist[3].append('cccc') print(c) # [1, 2, 3, ['a', 'b', 'cccc']] 虽然外层对象没改变,但里层的['a', 'b']已被改变 # 深拷贝,包含对象里面的自对象的拷贝,所以原始对象的改变不会造成深拷贝里任何子元素的改变 d=copy.deepcopy(alist) alist[3].append("ccccc") print(d) # [1, 2, 3, ['a', 'b'], 5] 里层外层都没有被改变,因为d已经完完全全跟alist没有关系了 ```