流程控制
https://docs.python.org/zh-cn/3/tutorial/controlflow.html#more-control-flow-tools
if语句
if x < 0:x = 0print('Negative changed to zero')elif x == 0:print('Zero')elif x == 1:print('Single')else:print('More')
for语句
遍历某个集合的同时修改该集合的内容,很难获取想要的结果。要在遍历时修改集合的内容,应该遍历该集合的副本或创建新的集合。
遍历拷贝对象
# Strategy: Iterate over a copyusers={"张三":'active',"李四":'inactive',"王五":'inactive'}for user,status in users.copy().items():if status == 'inactive':del users[user]print(users)
创建新的集合
# Strategy: Create a new collectionusers={"张三":'active',"李四":'inactive',"王五":'inactive'}active_users = {}for user, status in users.items():if status == 'active':active_users[user] = statusprint(active_users)
range函数
用于控制循环次数
# 执行循环5次for i in range(5):print(i)
生成等差数列(列表)
list(range(5, 10)) # 默认公差为1# [5, 6, 7, 8, 9]list(range(0, 10, 3)) # 公差为3# [0, 3, 6, 9]list(range(-10, -100, -30)) # 公差为-30
按索引进行循环
a = ['Mary', 'had', 'a', 'little', 'lamb']for i in range(len(a)):print(i, a[i])
注意:range()的返回值为一个可迭代对象,而不是一组数字。range() 返回对象的操作和列表很像,但其实这两种对象不是一回事。迭代时,该对象基于所需序列返回连续项,并没有生成真正的列表,从而节省了空间
for-else语句
for循环中正常结束时则会执行else语句中的内容,未能正常结束(如break)则不执行
# 该语句中若执行到了break,则else语句不会执行。for n in range(2, 10):for x in range(2, n):if n % x == 0:print(n, 'equals', x, '*', n//x)breakelse:print(n, 'is a prime number')
pass语句
pass 语句不执行任何操作。语法上需要一个语句,但程序不实际执行任何动作时,可以使用该语句。如空循环,空类,占位符。
函数
默认参数
def ask_ok(prompt, retries=4, reminder='Please try again!'):while True:ok = input(prompt)if ok in ('y', 'ye', 'yes'):return Trueif ok in ('n', 'no', 'nop', 'nope'):return Falseretries = retries - 1if retries < 0:raise ValueError('invalid user response')print(reminder)
重要警告: 默认值只计算一次。默认值为列表、字典或类实例等可变对象时,会产生与该规则不同的结果。例如,下面的函数会累积后续调用时传递的参数:
def f(a, L=[]):L.append(a)return Lprint(f(1))print(f(2))print(f(3))"""[1][1, 2][1, 2, 3]"""# 正确用法:def f(a, L=None):if L is None:L = []L.append(a)return L
关键词参数
可以通过kwarg=value形式的关键字参数调用函数。
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):print("-- This parrot wouldn't", action, end=' ')print("if you put", voltage, "volts through it.")print("-- Lovely plumage, the", type)print("-- It's", state, "!")parrot(1000) # 1 positional argumentparrot(voltage=1000) # 1 keyword argumentparrot(voltage=1000000, action='VOOOOOM') # 2 keyword argumentsparrot(action='VOOOOOM', voltage=1000000) # 2 keyword argumentsparrot('a million', 'bereft of life', 'jump') # 3 positional argumentsparrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
接受元组和字典
最后一个形参为 name 形式时,接收一个字典(详见 映射类型 —- dict),该字典包含与函数中已定义形参对应之外的所有关键字参数。name 形参可以与 name 形参(下一小节介绍)组合使用(name 必须在 *name 前面), name 形参接收一个 元组,该元组包含形参列表之外的位置参数。例如,可以定义下面这样的函数:
def cheeseshop(kind, *arguments, **keywords):print("-- Do you have any", kind, "?")print("-- I'm sorry, we're all out of", kind)# print(type(arguments)) #<class 'tuple'>for arg in arguments:print(arg)print("-" * 40)#print(type(keywords)) #<class 'dict'>for kw in keywords:print(kw, ":", keywords[kw])cheeseshop("Limburger", "It's very runny, sir.","It's really very, VERY runny, sir.",shopkeeper="Michael Palin",client="John Cleese",sketch="Cheese Shop Sketch")
位置参数和关键词参数
使用”/“和”“来限制参数传递的方式是位置传递或者关键词参数,”/“前的是位置参数,不可以通过关键词方式传参,后为关键词参数,不可以通过位置参数传递。
def combined_example(pos_only, /, standard, *, kwd_only):print(pos_only, standard, kwd_only)combined_example(1, 2, kwd_only=3)
可变参数
使用或者*传入元组或者字典达到可变参数的效果。
def concat(*args, sep="/"): ## 传入元组return sep.join(args)print(concat("earth", "mars", "venus"))
参数传递-容器展开
# 列表展开 作为位置参数args = [3, 6]print(*args)# 字典展开 作为关键词参数def parrot(voltage, state='a stiff', action='voom'):print("-- This parrot wouldn't", action, end=' ')print("if you put", voltage, "volts through it.", end=' ')print("E's", state, "!")d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}parrot(**d)
lambda表达式
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]pairs.sort(key=lambda pair: pair[1])print(pairs)
数据结构
https://docs.python.org/zh-cn/3/tutorial/datastructures.html#data-structures
列表
列表常用操作
list.append(x)在列表末尾添加一个元素,相当于 a[len(a):] = [x] 。list.extend(iterable)用可迭代对象的元素扩展列表。相当于 a[len(a):] = iterable 。list.insert(i, x)在指定位置插入元素。第一个参数是插入元素的索引,因此,a.insert(0, x) 在列表开头插入元素,a.insert(len(a), x) 等同于 a.append(x) 。list.remove(x)从列表中删除第一个值为 x 的元素。未找到指定元素时,触发 ValueError 异常。list.pop([i])删除列表中指定位置的元素,并返回被删除的元素。未指定位置时,a.pop() 删除并返回列表的最后一个元素。(方法签名中 i 两边的方括号表示该参数是可选的,不是要求输入方括号。这种表示法常见于 Python 参考库)。list.clear()删除列表里的所有元素,相当于 del a[:] 。list.index(x[, start[, end]])返回列表中第一个值为 x 的元素的零基索引。未找到指定元素时,触发 ValueError 异常。可选参数 start 和 end 是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 start 参数。list.count(x)返回列表中元素 x 出现的次数。list.sort(*, key=None, reverse=False)就地排序列表中的元素(要了解自定义排序参数,详见 sorted())。list.reverse()反转列表中的元素。list.copy()返回列表的浅拷贝。相当于 a[:] 。
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']ret=fruits.count('apple')print(ret)ret=fruits.index('banana')print(ret)ret=fruits.index('banana', 4) # Find next banana starting a position 4print(ret)fruits.reverse()print(fruits)fruits.append('grape')print(fruits)fruits.sort()print(fruits)ret=fruits.pop()print(ret)
列表推导式
列表推导式创建列表的方式更简洁。常见的用法为,对序列或可迭代对象中的每个元素应用某种操作,用生成的结果创建新的列表;或用满足特定条件的元素创建子序列。
列表推导式的方括号内包含以下内容:一个表达式,后面为一个 for 子句,然后,是零个或多个 for 或 if 子句。结果是由表达式依据 for 和 if 子句求值计算而得出一个新列表。
squares = [x**2 for x in range(10)][(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
嵌套的列表推导式
matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],]# 矩阵转置ret= [[row[i] for row in matrix] for i in range(4)]print(ret)# [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
del语句
删除列表中元素
del语句作用在变量上,而不是数据对象上。
a = [-1, 1, 66.25, 333, 333, 1234.5]first = a[0]del a[0]print(a) # [1, 66.25, 333, 333, 1234.5]print(first) # -1
if __name__=='__main__':a=1 # 对象 1 被 变量a引用,对象1的引用计数器为1b=a # 对象1 被变量b引用,对象1的引用计数器加1c=a #1对象1 被变量c引用,对象1的引用计数器加1del a #删除变量a,解除a对1的引用del b #删除变量b,解除b对1的引用print(c) #最终变量c仍然引用1if __name__=='__main__':li=[1,2,3,4,5] #列表本身不包含数据1,2,3,4,5,而是包含变量:li[0] li[1] li[2] li[3] li[4]first=li[0] #拷贝列表,也不会有数据对象的复制,而是创建新的变量引用del li[0]print(li) #输出[2, 3, 4, 5]print(first) #输出 1
元组
https://docs.python.org/zh-cn/3/tutorial/datastructures.html#tuples-and-sequences
声明一个元组,声明元组可以不使用圆括号,当元组嵌套时,建议使用圆括号。
t = 12345, 54321, 'hello!'t[0] #12345t #(12345, 54321, 'hello!')
元组可以嵌套
# Tuples may be nested:u = t, (1, 2, 3, 4, 5)u #((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
元组内容是不可变的
# Tuples are immutable:t[0] = 88888Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment
元组中可以存放内容可变对象(如列表)
v = ([1, 2, 3], [3, 2, 1])v[0][1] = 3print(v) #([1, 3, 3], [3, 2, 1])
空元组和单元素元组 ```python
空元组
empty = () print(empty,type(empty)) # ()
singleton = 10,
print(singleton,type(singleton)) #(10,)
tmp = (10)
print(tmp,type(tmp)) #10
- 元组打包和解包```pythont = 12345, 54321, 'hello!' #元组打包a,b,c = t # 元组解包x,y,z = "a","b","c" #多重复制 为元组打包和解包
集合
集合是由不重复元素组成的无序容器。基本用法包括成员检测、消除重复元素。集合对象支持合集、交集、差集、对称差分等数学运算。
创建
空集合只能用set()方法创建,直接使用{}会创建空字典。
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
集合运算
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}## 集合去重print(basket) #{'banana', 'pear', 'orange', 'apple'}## 集合测试元素存在print('apple' in basket) # True## 集合关系运算a=set("abcdedg") # 注意a为字符集合长度为7 而a={"abcdedg"} 则只有1个元素print(a)b = set('alacazam')print(b)# 交运算print(a & b) # {'c', 'a'}# 并运算print( a | b) # {'b', 'z', 'l', 'g', 'e', 'a', 'm', 'c', 'd'}# 差运算print(a-b) # {'e', 'g', 'b', 'd'}# 对称差分print(a^b) # {'z', 'b', 'g', 'e', 'm', 'l', 'd'}
字典
字典以关键字为索引,关键字通常是字符串或数字,也可以是其他任意不可变类型。只包含字符串、数字、元组的元组,也可以用作关键字。但如果元组直接或间接地包含了可变对象,就不能用作关键字。列表不能当关键字,因为列表可以用索引、切片、append() 、extend() 等方法修改。
## 创建空字典m = {}## dict() 构造函数构造 直接用键值对序列创建字典print(dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]))## dict() 直接用关键字参数指定键值d对print(dict(sape=4139, guido=4127, jack=4098))## 列表推导创建字典tmp = {x: x**2 for x in (2, 4, 6)}print(type(tmp)) # <class 'dict'>## 增加元素m["hello"] = 100print(m) #{'hello': 100}## 修改m["hello"]=10 #{'hello': 10}print(m)## 删除元素del m["hello"]print(m) #{}## 判断存在m["hello"]=0print("hello" in m) #True## 转为列表m["world"]=0print(list(m)) #['hello', 'world']## 排序 默认对索引值排序print(sorted(m)) #['hello', 'world']
字典按元素值排序:
import operatorclassCount={1:23,2:43,3:43,4:3}sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)sortedClassCount# [(2, 43), (3, 43), (1, 23), (4, 3)]
遍历
字典遍历
- 在字典中循环时,用 items() 方法可同时取出键和对应的值 。
knights = {'gallahad': 'the pure', 'robin': 'the brave'}for k, v in knights.items():print(k,"-",v)
列表遍历
序列中循环时,用 enumerate() 函数可以同时取出位置索引和对应的值。
同时循环两个或多个序列时,用 zip() 函数可以将其内的元素一一匹配。for i, v in enumerate(['tic', 'tac', 'toe']):print(i, v)
使用集合构造函数set()和sorted函数 遍历列表中的唯一元素questions = ['name', 'quest', 'favorite color']answers = ['lancelot', 'the holy grail', 'blue']for q, a in zip(questions, answers):print('What is your {0}? It is {1}.'.format(q, a))
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']for f in sorted(set(basket)):print(f)
map函数
https://www.runoob.com/python/python-func-map.html
map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表
