02-python语法基础
一、数据类型的基本操作
基本操作
- 连接两个字符串:+
- 重复字符串中的元素:*
- 统计字符串中元素数量:len()
- 判断某个字符是否在字符串中:in
- 查看方法(函数):dir()
- 查看文档:help()
- 对象类型:type()
- 内存地址:id()
- 绝对值:abs()
- 幂:pow()
- 四舍五入:round()
- 分数计算:import fractions
- 精确计算:import decimal
- 拓展视野:
- 科学计算专用工具库:scipy
- 符号运算专用工具库:sympy
- 线性代数专用工具库:numpy
字符串的方法(函数)——str
- 判断字符串是否只由纯数字组成——isdigit()
>>> "250ab".isdigit() False >>> st = '250ab' >>> st.isdigit() False >>> su = '250123' >>> su.isdigit() True
-
字符串分割——split()
- 字符串组合——join()
>>> s = "life is short you need python" >>> lst = s.split(' ') >>> lst ['life', 'is', 'short', 'you', 'need', 'python'] >>> "*".join(lst) 'life*is*short*you*need*python' >>> " ".join(lst) 'life is short you need python'
- 字符串格式化输出——format()
#{0}、{1}表示占位符 >>> "I like {0}".format("python") 'I like python' >>> "I like {0} and {1}".format("python","physics") 'I like python and physics' >>> "I like {0:10} and {1:>15}".format("python","physics") 'I like python and physics' >>> "I like {0:^10} and {1:>15}".format("python","physics") 'I like python and physics' #{0:10},表示字符串宽度为10 #{1:>15},表示字符串宽度为15,且右对齐 #{0:^10},表示python居中 >>> "She is {0:4d} years old and {1:.1f}m in height!".format(28,1.68) 'She is 28 years old and 1.7m in height!' #(数字默认是右对齐,字符串默认是左对齐) #{0:4d},表示左对齐放置整数,且宽度为4 #{1:.1f},表示左对齐放置浮点数,小数保留1位 >>> "She is {0:04d} years old and {1:06.1f}m in height!".format(28,1.68) 'She is 0028 years old and 0001.7m in height!' #{0:04d},表示左对齐,放置整数,宽度为4,空位用0补充 #{1:06.1f},表示左对齐,放置浮点数且保留一位小数,宽度为6,空位用0补充 #format格式化填充 >>> h = "hello" >>> format(h,'->20') '---------------hello' #进制数之间转换 >>> format(65,'b') '1000001' >>> format(65,'o') '101' >>> format(65,'x') '41'
布尔类型数据对象—bool
- 布尔类型的两个值:True、False
- 内置函数:bool
列表类型数据对象——list
- 增加列表的元素
- 列表尾部追加元素——append()
- 列表索引处新增元素——insert()
- 列表尾部追加列表或元素——extend()
- 删除列表中的元素
- 列表中删除元素且不返回删除的元素——remove()
- 列表中删除元素并返回删除的元素——pop()
- 清空列表的所有元素——clear()
- 列表元素的排序与反序
- 按由小到大排序——sort()
- 按由大到小排序——reverse()
- 内置函数(不改变原列表的元素):sorted、reversed()
- 列表的去重——set()
- 列表练习
- 找出某一列中等于或大于某个值的最大索引,比如A列的值有好几个相同,找出这个相同里面的最大索引位置
>>> lst=[1,2,4,5,8,4,11,4,3,7,12,2,5,2,3,49,6,7] >>> print(list(enumerate(lst))) [(0, 1), (1, 2), (2, 4), (3, 5), (4, 8), (5, 4), (6, 11), (7, 4), (8, 3), (9, 7), (10, 12), (11, 2), (12, 5), (13, 2), (14, 3), (15, 49), (16, 6), (17, 7)] >>> print([i for i,x in enumerate(lst) if x == 2]) [1, 11, 13] >>> print([i for i,x in enumerate(lst) if x == 3]) [8, 14] >>> max(lst) 49 >>> print([i for i,x in enumerate(lst) if x == max(lst)]) [15]
>>> print([i for i,x in enumerate(lst) if x >=7])
[4, 6, 9, 10, 15, 17]
元组类型数据对象——tuple
- 序列:字符串、列表、元组
- 索引和切片——与字符串相同
- 基本操作——与字符串相同
- 元组的元素不可以修改
- 这是与列表的区别
- 元组与列表直接的转换
>>> lst =(1,3.14,[1,2,3],'tuple',True,()) >>> lst (1, 3.14, [1, 2, 3], 'tuple', True, ()) >>> tlst = list(lst) >>> tlst [1, 3.14, [1, 2, 3], 'tuple', True, ()] >>> tuple(tlst) (1, 3.14, [1, 2, 3], 'tuple', True, ()) >>> lst (1, 3.14, [1, 2, 3], 'tuple', True, ())
#实际是通过list、tuple函数产生新的列表,再对新列表进行修改 >>> tlst[1] = 2.45 >>> tlst [1, 2.45, [1, 2, 3], 'tuple', True, ()] >>> lst (1, 3.14, [1, 2, 3], 'tuple', True, ()) >>>
- 元组的必要性
- 元组比列表操作速度快
- 元组能够对不需要修改的数据“写保护”
- 元组可以作为字典的键
字典数据对象——dict
字典的创建和组成
- dict{'key1':'value1','key2':'value2....'}
字典的基本操作
字典操作总结
-
- 字典键值对数量:len()
- 获取字典中键的取值:d[key]
- 修改字典中键的值:d[key]=value
- 判断键是否存在:key in d
- 删除键值对:del d[key]
- 取值get(不会报错):
- 设置默认值setdefault:dict.setdefault(key, default=None)
字典的基本方法(函数)
- 键值对的创建
>>> cities = ['shanghai','cooshow','hangzhou']
>>> phones = ['021','0512','0571']
>>> "{0}:{1}".format(cities[0],phones[0])
'shanghai:021'
#字典—键值对形式
>>> d = {'shanghai':'021','cooshow':'0512','hangzhou':'0571'}
>>> type(d)
<class 'dict'>
>>> {1:'a',2:['a','b'],(2,):['a','b'],'hello':{1:'a'},1:'python'}
{1: 'python', 2: ['a', 'b'], (2,): ['a', 'b'], 'hello': {1: 'a'}}
#字典的键不可重复,值可以重复
>>> {[1,2]:'hello'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
#可变类型list,不可用作字典的键
>>> dict() #空字典
{}
>>> dict(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> d
{'shanghai': '021', 'cooshow': '0512', 'hangzhou': '0571'}
- 键值对的获取——d.get()、d.setdefault()
#setdefault()方法:
#如果key和value都不存在,则创建key和value
#如果key和value都存在,则返回value值
#如果key存在,而value不赋值,则value值为None
>>> d
{'shanghai': '123', 'cooshow': '0512', 'hangzhou': '0571', 'beijing': '010', 'suzhou': '0520'}
>>> d['shanghai']
'123'
>>> d.setdefault('tianjing')
>>> d.setdefault('cooshow')
'0512'
>>> d.get('hangzhou')
'0571'
>>> d.setdefault('suzhou','0520')
'0520'
>>> d
{'shanghai': '123', 'cooshow': '0512', 'hangzhou': '0571', 'beijing': '010', 'suzhou': '0520', 'tianjing': None}
- 键值对的修改
>>> d['shanghai'] = '123'#修改字典的元素 >>> d {'shanghai': '123', 'cooshow': '0512', 'hangzhou': '0571'} >>> d.get('hangzhou') '0571' {'shanghai': '123', 'cooshow': '0512', 'hangzhou': '0571'} >>> d['beijing'] = '010' #新增字典的元素 >>> d {'shanghai': '123', 'cooshow': '0512', 'hangzhou': '0571', 'beijing': '010'}
- 键值对的追加——setdefault()、update()
>>> d.setdefault('suzhou','0520')
'0520'
>>> d
{'shanghai': '123', 'cooshow': '0512', 'hangzhou': '0571', 'beijing': '010', 'suzhou': '0520'}
>>> d.setdefault('tianjing')
>>> d
{'shanghai': '123', 'cooshow': '0512', 'hangzhou': '0571', 'beijing': '010', 'suzhou': '0520', 'tianjing': None}
>>> d1 = {'a':200,'b':300}
>>> d2 = {'name':'laoqi','age':28,'book':'python'}
>>> d2.update(d1)
>>> d2
{'name': 'laoqi', 'age': 28, 'book': 'python', 'a': 200, 'b': 300}
- 键值对的删除——pop()、popitem()、clear()
>>> d
{'shanghai': '123', 'hangzhou': '0571', 'suzhou': '0520', 'tianjing': None}
#pop删除指定的key
>>> d.pop('cooshow',404)
404
>>> d
{'shanghai': '123', 'hangzhou': '0571', 'suzhou': '0520', 'tianjing': None}
#popitem删除字典最后一个key
>>> d.popitem()
('tianjing', None)
>>> d
{'shanghai': '123', 'hangzhou': '0571', 'suzhou': '0520'}
#clear清空整个字典的key
>>> d.clear()
>>> d
{}
二、程序结构语句
逻辑运算
- not:逻辑非
- and:逻辑与
- or:逻辑或
- 优先级:()>not>and>or
##and:左边如果是false,则返回左边;否则返回右边
>>> 1 and 2
2
>>> 0 and 2
0
>>> 3<4 and 4>5
False
##or:左边如果是true,则返回左边;否则返回右边
>>> 1 or 2
1
>>> 0 or 2
2
>>> 3<4 or 4>5
True
##not:取反
>>> not 0
True
>>> not 1
False
>>> not 1 and 0##等价于 (not 1) and 0
False
>>> (not 1) and 0
False
>>> not (1 and 0)
True
##链式表达式
>>> 1 in [1,0]==True##等价于1 in [1,0] and [1,0]==True
False
>>> 1 in [1,0] and [1,0]==True
False
>>> 1 in [1,0]
True
>>> [1,0]==True
False
>>> 1==True
True
条件语句
- 单分支与多分支
- 字符串.isalnum() 所有字符都是数字或者字母,为真返回 Ture,否则返回 False。
- 字符串.isalpha() 所有字符都是字母,为真返回 Ture,否则返回 False。
- 字符串.isdigit() 所有字符都是数字,为真返回 Ture,否则返回 False。
- 字符串.islower() 所有字符都是小写,为真返回 Ture,否则返回 False。
- 字符串.isupper() 所有字符都是大写,为真返回 Ture,否则返回 False。
- 字符串.istitle() 所有单词都是首字母大写,为真返回 Ture,否则返回 False。
- 字符串.isspace() 所有字符都是空白字符,为真返回 Ture,否则返回 False。
[oldboy@linux-node3 ~]$ cat judge_num.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Version:1.0 # Date:2020-12-10 21:30 # Filename: query_cyle.py # Software: vscode-1.14.10 # Description:This script is used for """ def judge_number(): count = 0 instr = input("Please input your digit number:") if instr.isdigit(): n = int(instr) if n%2 == 0: print("your number {0} is 偶数".format(n)) print(n) else: print("your number {0} is 奇数".format(n)) print(n) else: print("Input error! requred a digit number.") judge_number() [oldboy@linux-node3 ~]$ python3 judge_num.py Please input your digit number:5 your number 5 is 奇数 5 [oldboy@linux-node3 ~]$ python3 judge_num.py Please input your digit number:4a Input error! requred a digit number.
for循环
- 迭代对象范文——range()
- 创建列表的对应元素的对应关系——zip()
- 列表索引——enumerate()
>>> a = range(5) >>> a range(0, 5) >>> for i in a: ... print(i) ... 0 1 2 3 4 5 >>> a = [1,2,3,4] >>> b = [5,6,7,8] >>> z = zip(a,b) >>> z <zip object at 0x7f8445626870> >>> list(zip(a,b)) [(1, 5), (2, 6), (3, 7), (4, 8)] >>> c = ['a','b','c','d'] >>> q = zip(a,c) >>> list(zip(a,c)) [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] #求和方式1: >>> for i in range(len(a)): ... print(a[i] + b[i]) ... 6 8 10 12 #求和方式2: >>> lst = [] >>> for x,y in zip(a,b): ... lst.append(x + y) ... >>> lst [6, 8, 10, 12]
>>> seasons = ['spring','summer','fall','winter'] >>> for i in range(len(seasons)): ... print(i,seasons[i]) ... 0 spring 1 summer 2 fall 3 winter >>> list(enumerate(seasons)) [(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')] >>> for i,e in enumerate(seasons): ... print(i,e) ... 0 spring 1 summer 2 fall 3 winter
- 列表解析(list comprehension)
- 参考地址:https://www.cnblogs.com/liu-shuai/p/6098227.html
#1、要求:列出1~10所有数字的平方除以2的值
1)普通方法
>>> L = []
>>> for i in range(1,11):
... L.append(i**2/2)
...
>>> print L
[0, 2, 4, 8, 12, 18, 24, 32, 40, 50]
2)列表解析
>>> L = [i**2/2 for i in range(1,11) ]
>>> print L
[0, 2, 4, 8, 12, 18, 24, 32, 40, 50]
#2、要求:列出1~10所有数字的平方除以2的值
1)普通方法
>>> L = []
>>> for i in range(1,11):
... L.append(i**2/2)
...
>>> print L
[0, 2, 4, 8, 12, 18, 24, 32, 40, 50]
2)列表解析
>>> L = [i**2/2 for i in range(1,11) ]
>>> print L
[0, 2, 4, 8, 12, 18, 24, 32, 40, 50]
#3、要求:实现两个列表中的元素逐一配对。
1)普通方法:
>>> L1 = ['x','y','z']
>>> L2 = [1,2,3]
>>> L3 = []
>>> for a in L1:
... for b in L2:
... L3.append((a,b))
...
>>> print L3
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
2)列表解析:
>>> L1 = ['x','y','z']
>>> L2 = [1,2,3]
L3 = [ (a,b) for a in L1 for b in L2 ]
>>> print L3
[('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
#其他解析
>>> d = {'a':1,'b':2,'c':3,'d':4}
>>> {v:k for k,v in d.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> {v:k for k,v in d.items() if v%2==0}
{2: 'b', 4: 'd'}
while循环
##求指定范围内的素数
>>> for n in range(2,10): ... for x in range(2,n): ... if n % x == 0: ... print(n,'=',x,'*',n/x) ... break ... else: ... print(n,"is a prime number") ... 2 is a prime number 3 is a prime number 4 = 2 * 2.0 5 is a prime number 6 = 2 * 3.0 7 is a prime number 8 = 2 * 4.0 9 = 3 * 3.0
字典解析
>>> tmp = {x:[x, x+1] for x in range(10)}
>>> print(tmp)
{0: [0, 1], 1: [1, 2], 2: [2, 3], 3: [3, 4], 4: [4, 5], 5: [5, 6], 6: [6, 7], 7: [7, 8], 8: [8, 9], 9: [9, 10]}
>>> my_num = {i:i for i in range(1,6)}
>>> print(my_num)
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
>>> nums = {str(i):i for i in range(1,6) if i %2 ==1 }
>>> print(nums)
{'1': 1, '3': 3, '5': 5}
- 将以下字典中的None值去掉
data = {"id":1,"first_name":"jonathan","middle_name":None,"last_name":"Hsu"}
>>> data = {"id":1,"first_name":"jonathan","middle_name":None,"last_name":"Hsu"} >>> {k:v for (k,v) in data.items()} {'id': 1, 'first_name': 'jonathan', 'middle_name': None, 'last_name': 'Hsu'} >>> {k:v for (k,v) in data.items() if v !=None} {'id': 1, 'first_name': 'jonathan', 'last_name': 'Hsu'}
- 将字典的值变成大写
data = {"first_name":"jonathan","last_name":"Hsu"}
>>> dt = {"first_name":"jonathan","last_name":"Hsu"}
>>> {k:v.upper() for (k,v) in dt.items()} {'first_name': 'JONATHAN', 'last_name': 'HSU'}
合并字典
- update()方法
>>> d1 = {"id":1,"first_name":"jonathan"} >>> d2 = {"first_name":"jonathan","last_name":"Hsu"} >>> d3 = d1.copy() >>> d3.update(d2) >>> d3 {'id': 1, 'first_name': 'jonathan', 'last_name': 'Hsu'}
- 解包方法
>>> d1 = {"a":1,"b":2} >>> d2 = {"c":3,"d":4} >>> d3 = {**d1,**d2} >>> d3 {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> d4 = {"c":3,"e":4} >>> d5 = {**d2,**d4} >>> d5 {'c': 3, 'd': 4, 'e': 4}
- dict(iterable,**kwarg)
>>> d1 = {"a":1,"b":2} >>> d2 = {"c":3,"d":4} >>> d3 = dict(d1,**d2) >>> d3 {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> d4 = {"id":1,"first_name":"jonathan"} >>> d5 = dict(d1,**d2,**d4) >>> d5 {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'id': 1, 'first_name': 'jonathan'}
异常处理
逻辑错误
>>> r = 10 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
语法错误——又称解析错误
>>> for i in range(10) File "<stdin>", line 1 for i in range(10) ^ SyntaxError: invalid syntax
- 单行捕获异常
[oldboy@linux-node3 ~]$ cat try_except_error.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Filename: query_cyle.py # Description:This script is used for """ while True: try: x = int(input("input an int number:")) r = 10 / x print(r) except: print("you should not input zero.") break [oldboy@linux-node3 ~]$ python3 try_except_error.py input an int number:2 5.0 input an int number:5 2.0 input an int number:4da you should not input zero.
- 多行捕获异常
[oldboy@linux-node3 ~]$ cat try_except_error.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Filename: query_cyle.py # Description:This script is used for """ while True: try: x = int(input("input an int number:")) r = 10 / x print(r) except ZeroDivisionError: print("you should not input zero.") break except SyntaxError: print("input an int number.") [oldboy@linux-node3 ~]$ python3 try_except_error.py input an int number:2 5.0 input an int number:2w Traceback (most recent call last): File "try_except_error.py", line 11, in <module> x = int(input("input an int number:")) ValueError: invalid literal for int() with base 10: '2w' [oldboy@linux-node3 ~]$ python3 try_except_error.py input an int number:0 you should not input zero.
- 合并捕获
[oldboy@linux-node3 ~]$ cat try_except_error_v2.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Filename: query_cyle.py # Description:This script is used for """ while True: try: x = int(input("input an int number:")) r = 10 / x print(r) except (ZeroDivisionError,SyntaxError) as e: print(e) #print("you should not input zero.") break # except SyntaxError: # print("input an int number.") [oldboy@linux-node3 ~]$ python3 try_except_error_v2.py input an int number:4 2.5 input an int number:2w Traceback (most recent call last): File "try_except_error_v2.py", line 11, in <module> x = int(input("input an int number:")) ValueError: invalid literal for int() with base 10: '2w' [oldboy@linux-node3 ~]$ python3 try_except_error_v2.py input an int number:0 division by zero
- 异常分支
try无异常则执行else语句;否则执行except语句捕获异常
无论是否有异常,finally语句都会被执行
[oldboy@linux-node3 ~]$ cat try_except_error_v2.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Filename: query_cyle.py # Description:This script is used for """ while True: try: x = int(input("input an int number:")) r = 10 / x print(r) except (ZeroDivisionError,SyntaxError) as e: print(e) #print("you should not input zero.") break finally: print("goodbye") break # except SyntaxError: # print("input an int number.") [oldboy@linux-node3 ~]$ python3 try_except_error_v2.py input an int number:5 2.0 goodbye [oldboy@linux-node3 ~]$ python3 try_except_error_v2.py input an int number:0 division by zero goodbye [oldboy@linux-node3 ~]$ python3 try_except_error_v2.py input an int number:2w goodbye
- 抛出异常——raise
- 断言——assert()
#主动抛出raise异常
[oldboy@linux-node3 ~]$ cat try_except_error_v3.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Filename: query_cyle.py # Description:This script is used for """ while True: try: age = int(input("How old are you?:")) assert age > 0 if age > 150: raise ValueError("Are you a god?") elif (age <= 150) and (age > 80): print("Wish you good health") elif (age <= 80) and (age >60): print("A new life begins.") elif (age <= 60) and (age >30): print("Word hard") else: print("I envy you") except ValueError: print("Find your glasses.") break [oldboy@linux-node3 ~]$ python3 try_except_error_v3.py How old are you?:123 Wish you good health How old are you?:80 A new life begins. How old are you?:0 Traceback (most recent call last): File "try_except_error_v3.py", line 12, in <module> assert age > 0 AssertionError
#捕获AssertionError异常
[oldboy@linux-node3 ~]$ cat try_except_error_v3.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Filename: query_cyle.py # Description:This script is used for """ while True: try: age = int(input("How old are you?:")) assert age > 0 if age > 150: raise ValueError("Are you a god?") elif (age <= 150) and (age > 80): print("Wish you good health") elif (age <= 80) and (age >60): print("A new life begins.") elif (age <= 60) and (age >30): print("Word hard") else: print("I envy you") except (ValueError,AssertionError): print("Find your glasses.") break [oldboy@linux-node3 ~]$ python3 try_except_error_v3.py How old are you?:180 Find your glasses. [oldboy@linux-node3 ~]$ python3 try_except_error_v3.py How old are you?:45 Word hard How old are you?:0 Find your glasses. [oldboy@linux-node3 ~]$ python3 try_except_error_v3.py How old are you?:-19 Find your glasses.
python列表、元组、字典、集合、字符串相互转换
- 知乎地址:https://zhuanlan.zhihu.com/p/82703713
- 集合:交集、并集、差集、对称差集
- 并集
>>> friends1 = {"zero","kevin","jason","egon"} >>> friends2 = {"Jy","ricky","jason","egon"} >>> friends1 | friends2 {'zero', 'Jy', 'ricky', 'kevin', 'jason', 'egon'} >>> friends1.union(friends2) {'zero', 'Jy', 'ricky', 'kevin', 'jason', 'egon'}
-
- 交集
>>> friends1 = {"zero","kevin","jason","egon"} >>> friends2 = {"Jy","ricky","jason","egon"} >>> friends1.intersection(friends2) {'jason', 'egon'} >>> friends1 & friends2 {'jason', 'egon'}
-
- 差集
>>> friends1 = {"zero","kevin","jason","egon"} >>> friends2 = {"Jy","ricky","jason","egon"} >>> friends1 - friends2 {'zero', 'kevin'} >>> friends1.difference(friends2) {'zero', 'kevin'}
-
- 对称差集
>>> friends1 = {"zero","kevin","jason","egon"} >>> friends2 = {"Jy","ricky","jason","egon"} >>> friends1.symmetric_difference(friends2) {'zero', 'Jy', 'ricky', 'kevin'} >>> friends1 ^ friends2 {'zero', 'Jy', 'ricky', 'kevin'}
- 需求示例
""" 一.关系运算 有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合 pythons={'jason','egon','kevin','ricky','gangdan','biubiu'} linuxs={'kermit','tony','gangdan'} 1. 求出即报名python又报名linux课程的学员名字集合 2. 求出所有报名的学生名字集合 3. 求出只报名python课程的学员名字 4. 求出没有同时这两门课程的学员名字集合 """ # 求出即报名python又报名linux课程的学员名字集合 >>> pythons & linuxs # 求出所有报名的学生名字集合 >>> pythons | linuxs # 求出只报名python课程的学员名字 >>> pythons - linuxs # 求出没有同时这两门课程的学员名字集合 >>> pythons ^ linuxs
- 父集、子集
>>> s1={1,2,3} >>> s2={1,2} >>> {1,2,3} > {1,2}#父集 True >>> {1,2,3} >= {1,2} True >>> {1,2,3} >= {1,2,3,5} False >>> {1,2} < {1,2,3}#子集 True >>> {1,2} <= {1,2,3} True >>> s1 > s2 True >>> s2 < s1 True >>> s1.issuperset(s2)#父集 True >>> s2.issubset(s1)#子集 True
-
集合内置方法
- discard、update、add、isdisjoint
>>> s1={1,2,3} >>> s2={1,2} >>> s1.discard({1,3}) >>> s1 {1, 2, 3} >>> s1.discard(3)#将集合中元素删除,不存在不报错;remove删除,不存在则报错 >>> s1 {1, 2} >>> s1.discard(4) >>> s1 {1, 2} >>> s1.update({5,6}) >>> s1 {1, 2, 5, 6} >>> s1.discard({4,7}) >>> s1 {1, 2, 5, 6} >>> s1.difference_update(s2)#交集 >>> s1 {5, 6} >>> s2 {1, 2} >>> s1.add(4) >>> s1 {4, 5, 6} >>> s1.isdisjoint(s2)#两个集合完全独立,即没有交集,返回true True
函数与高阶函数
内置函数
自定义函数
- 定义函数——例题:编写函数,查找某个范围内自然数中的所有素数
[oldboy@linux-node3 ~]$ cat judge_premi_num.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Version:1.0 # Description:This script is used for """ import math def is_primel(nlst): primels = [] for n in nlst: for x in range(2,n): if n % x == 0: break else: primels.append(n) return primels ns = range(2,100) print(is_primel(ns)) [oldboy@linux-node3 ~]$ python3 judge_premi_num.py [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Version:1.0 # Description:This script is used for """ def search_prime_number(x, y): number = [] for i in range(2, y): for j in range(2, i): if i % j == 0: break else: number.append(i) return number print("请输入您要输入的自然数范围:如2~5,即x=2,y=5") x = int(input("x=")) y = int(input("y=")) print("您输入的自然数范围为{0}~{1}".format(x,y)) z = search_prime_number(x,y+1) print("{0}至{1}的素数为:{2}".format(x,y,z))
函数调用
- 调用方式
- 传参数的方式——按照位置;根据名称;设置默认值
- 注意
- 通常不对函数的参数所引用的对象类型进行检查
- 可以用pass关键词定义函数
- 函数名称代表函数对象
#按照位置 >>> def foo(x,y): ... print("x=",x) ... print("y=",y) ... >>> foo(3,4) x= 3 y= 4 >>> foo(4,3) x= 4 y= 3 #根据名称 >>> foo(x=4,y=3) x= 4 y= 3 >>> foo(y=4,x=3) x= 3 y= 4 #设置默认值 >>> def foo(x,y): ... print("x=",x) ... print("y=",y) ... return x +y ... >>> foo(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() missing 1 required positional argument: 'y' >>> foo(2,5) x= 2 y= 5 7 >>> def foo(x,y=4): ... print("x=",x) ... print("y=",y) ... return x +y ... >>> foo(4) x= 4 y= 4 8
函数的返回值与参数收集方法
-
函数的返回值——return语句
案例1:编写斐波那契数列(也称兔子数列)函数
说明:斐波那契数列指的是这样一个数列:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610。。。
[oldboy@linux-node3 ~]$ cat fibs_cacula_num.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Version:1.0 # Description:This script is used for """ def fibs(n): res = [0,1] for i in range(n-2): res.append(res[-2] + res[-1]) return res num = int(input("请输入想要查询的斐波那契数列的值:")) cnum = fibs(num) print("斐波那契数列值为:",cnum) [oldboy@linux-node3 ~]$ [oldboy@linux-node3 ~]$ python3 fibs_cacula_num.py 请输入想要查询的斐波那契数列的值:2 斐波那契数列值为: [0, 1] [oldboy@linux-node3 ~]$ python3 fibs_cacula_num.py 请输入想要查询的斐波那契数列的值:5 斐波那契数列值为: [0, 1, 1, 2, 3] [oldboy@linux-node3 ~]$ python3 fibs_cacula_num.py 请输入想要查询的斐波那契数列的值:10 斐波那契数列值为: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
案例2:在0~100之间随机去1000个整数,这些数组成一个列表,请计算列表中所有数的平均数和标准差
#老师的方法 [oldboy@linux-node3 ~]$ cat sum_avg_num.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:chengzi # Version:1.0 # Description:This script is used for """ import random def mean(lst): s = sum(lst) n = len(lst) return s / n def standard_deviation(lst): import math mean = sum(lst) / len(lst) bias_mean = [(x - mean)**2 for x in lst] s2 = sum(bias_mean) / len(bias_mean) return math.sqrt(s2) lst = [random.randint(0, 100) for i in range(10000)] avg = mean(lst) sta = standard_deviation(lst) print(lst) print("average is:",avg) print("standard_deviation is:",sta)
参数的收集——主要是"*"的作用参数
- 参数
- *arg
- **kwargs
- 变量
- x,y = 1,2,3,4
嵌套函数——在一个函数中定义了另外一个函数
返回函数
- 将函数作为返回值
- 返回内置函数对象
- 返回自定义函数对象
>>> def foo(): ... def bar(): ... print("I am in bar") ... print("I am in foo") ... >>> foo() I am in foo >>> def foo(): ... def bar(): ... print("I am in bar") ... print("I am in foo") ... bar() ... >>> foo() I am in foo I am in bar
>>> def foo(): ... def bar(): ... print("I am in bar") ... print("I am in foo") ... return bar ... >>> b = foo() I am in foo >>> b() I am in bar
- 变量作用域——指变量的有效范围
- 函数内部的局部(本地)作用
- 嵌套函数内
- 嵌套函数之外但在外层函数之内
- 函数内部的局部(本地)作用
def a(): ## 局部变量 - ,- local = 1 print(local) ## 全局无法使用,只有自己可用 print(lobal)
-
- 全局作用域
global_str = '123' def a(): ## 全局变量 - ,- print(global_str) ## 全局变量大家都可以用 print(global_str)
-
- 内置作用域
系统内固定模块里定义的变量,如预定义在builtin 模块内的变量
- 作用域的划分
- 根据代码结构划分不同级别的作用域:(块级)、函数、类、模块、包
- python中,if语句块、for语句块、with上下文管理器等等不能划分变量作用域
- 函数和类改变作用域:def、class、lambda
- 搜索规则
- 从内向外,逐层搜索,找到则停止
-
- 作用域取决于代码块在整体代码中的位置
- 例如函数代码块的位置,而与函数调用的位置无关
- 作用域取决于代码块在整体代码中的位置
- 作用域两个关键词
- global:指定点前变量使用外部的全局变量
- nonlocal:内层函数中的变量它外一层函数的变量
案例:利用嵌套函数知识,编写实现“一元二次函数”的程序
[oldboy@linux-node3 ~]$ cat unary_quadratic_func.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:ChengZi # Version:1.0 # Description:This script is used for 利用嵌套函数知识,编写实现“一元二次函数”的程序 y = ax^2 + bx + c """ def parabola(a,b,c): def para(x): return a * x * x + b * x +c return para y = parabola(2,3,4) r = y(3) print("y = 2x^2 + 3x + 4\nx=3, the result = {0}".format(r)) [oldboy@linux-node3 ~]$ python3 unary_quadratic_func.py y = 2x^2 + 3x + 4 x=3, the result = 31
简单的装饰器
从嵌套函数到语法糖@
没有参数的装饰器
[oldboy@linux-node3 ~]$ cat def_strong_book.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:ChengZi # Version:1.0 # Description:This script is used for """ def book(name): return name def strong_deco(f): def wrapper(name): return "<strong>{0}</strong>".format(f(name)) return wrapper my = strong_deco(book) book = my("Learn Python") print(book) [oldboy@linux-node3 ~]$ python3 def_strong_book.py <strong>Learn Python</strong>
[oldboy@linux-node3 ~]$ cat strong_book_wrapper.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:ChengZi # Version:1.0 # Description:This script is used for """ def strong_deco(f): def wrapper(name): return "<strong>{0}</strong>".format(f(name)) return wrapper #my = strong_deco(book) #book = my("Learn Python") @strong_deco def book(name): return name b = book("Learn Python") print(b) [oldboy@linux-node3 ~]$ python3 strong_book_wrapper.py <strong>Learn Python</strong>
案例:编写一个用于测试函数执行时间的装饰器
#对比for循环和列表解析的运行速度 [oldboy@linux-node3 ~]$ cat timing_cacul_func.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ # Author:ChengZi # Version:1.0 # Description:This script is used for """ import time def timing_func(func): def wrapper(): start = time.time() func() stop = time.time() return (start - stop) return wrapper @timing_func def test_list_append(): lst = [] for i in range(0,100000): lst.append(i) @timing_func def test_list_compre(): [i for i in range(0,100000)] a = test_list_append() c = test_list_compre() print("test list append time:",a) print("test list comprehension time:",c) print("append/compre:",round(a/c,3)) [oldboy@linux-node3 ~]$ python3 timing_cacul_func.py test list append time: -0.02111959457397461 test list comprehension time: -0.010787487030029297 append/compre: 1.958
特殊函数:lambda、map、filter
同一种操作的多种方法
lambda函数:
- 语法:lambda arg1,arg2,arg3...,argn:expre(args)
案例:
>>> lam = lambda x,y:x + y >>> type(lam) <class 'function'> >>> def add(x,y): ... return x + y ... >>> add(5,6) 11 >>> lam(5,8) 13
#使用列表解析
>>> n = range(-5,5) >>> [True if i>0 else False for i in n] [False, False, False, False, False, False, True, True, True, True]
#使用lambda函数 >>> [(lambda x:x>0)(i) for i in n] [False, False, False, False, False, False, True, True, True, True]
map函数:
- 语法:map(func,*iterables) —》map object
案例:
#列表解析、lambda和map >>> [i+1 for i in range(10)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [(lambda x:x + 1)(i) for i in range(10)] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> m = map(lambda x:x + 1,range(10)) >>> m <map object at 0x7fa9ab6881d0> >>> list(m) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> a = [1,2,3] >>> b = [4,5,6] >>> [x+y for x,y in zip(a,b)] [5, 7, 9] >>> r = map(lambda x,y:x+y,a,b) >>> list(r) [5, 7, 9]
#计算列表各个元素的平方 >>>def square(x): ... return x ** 2 ... >>> map(square, [1,2,3,4,5]) [1, 4, 9, 16, 25]
# 使用lambda匿名函数 >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) [1, 4, 9, 16, 25] #提供了两个列表,对相同位置的列表数据进行相加 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19]
filter函数(过滤器):
- 语法:filter(func or None,*iterables) —》map object
案例:
>>> n range(-5, 5) >>> f = filter(lambda x:x>0,n) >>> f <filter object at 0x7fa9ab688c90> >>> list(f) [1, 2, 3, 4] >>> [i for i in n if i>0] [1, 2, 3, 4]
海象运算符(py3.8+新增的运算符)
本质上是赋值语句
- 语法:
- a = b
- a := b
- 不用海象运算符,可以编辑
- 使用海象运算符,让程序更精炼
实例1:
fresh_fruit = { 'apple': 10, 'banana': 8, 'lemon': 5, } #计算价格 def make_lemonade(count): ... def out_of_stock(): ... #普通判断 count = fresh_fruit.get('lemon', 0) if count: make_lemonade(count) else: out_of_stock() #使用海象运算符 if count := fresh_fruit.get('lemon', 0): make_lemonade(count) else: out_of_stock()
实例2:
#普通算法 count = fresh_fruit.get('banana', 0) if count >= 2: pieces = slice_bananas(count) else: pieces = 0 try: smoothies = make_smoothies(pieces) except OutOfBananas: out_of_stock() #使用海象运算符 pieces = 0 if (count := fresh_fruit.get('banana', 0)) >= 2: pieces = slice_bananas(count) try: smoothies = make_smoothies(pieces) except OutOfBananas: out_of_stock() #使用海象运算符,提高pieces的可读性 if (count := fresh_fruit.get('banana', 0)) >= 2: pieces = slice_bananas(count) else: pieces = 0 try: smoothies = make_smoothies(pieces) except OutOfBananas: out_of_stock()
count = fresh_fruit.get('banana', 0) if count >= 2: pieces = slice_bananas(count) to_enjoy = make_smoothies(pieces) else: count = fresh_fruit.get('apple', 0) if count >= 4: to_enjoy = make_cider(count) else: count = fresh_fruit.get('lemon', 0) if count: to_enjoy = make_lemonade(count) else: to_enjoy = 'Nothing'
#使用海象运算符,提高代码的可读性 if (count := fresh_fruit.get('banana', 0)) >= 2: pieces = slice_bananas(count) to_enjoy = make_smoothies(pieces) elif (count := fresh_fruit.get('apple', 0)) >= 4: to_enjoy = make_cider(count) elif count := fresh_fruit.get('lemon', 0): to_enjoy = make_lemonade(count) else: to_enjoy = 'Nothing'
注意事项:
- 在单个表达式中同时对变量名进行赋值和计算,从而减少重复
- 当赋值表达式是一个较大表达式的子表达式时,必须用圆括号括起来
>>> friends1.intersection(friends2){'jason', 'egon'}