条件判断
match…case
Python 3.10 增加了 match…case 的条件判断,不需要再使用一连串的 if-else 来判断了。
match 后的对象会依次与 case 后的内容进行匹配,如果匹配成功,则执行匹配到的表达式,否则直接跳过,”_” 可以匹配一切。
1 2 3 4 5 6 7 8
| value = input() match value: case 10: print('10') case 11: print('11') case _: print('_')
|
循环语句
while…else…
如果 while 后面的条件语句为 false 时,则执行 else 的语句块。
1 2 3 4 5 6
| count = 0 while count < 5: print (count, " 小于 5") count = count + 1 else: print (count, " 大于或等于 5")
|
for…else…
和while…else…一样,当不满足for循环的条件时就执行else语句,用于在循环结束后执行一段代码。
break用于跳出循环,而else属于循环的一部分,所以break会跳过else的执行。
1 2 3 4 5 6 7
| arr=[1,2,3,4,5,6,7] for index in range(len(arr)): if index>=3: break print(arr[index]) else: print("数组越界")
|
推导式
列表推导式
语法:
1 2 3 4 5
| [表达式 for 变量 in 列表] [out_exp_res for out_exp in input_list] 或者 [表达式 for 变量 in 列表 if 条件] [out_exp_res for out_exp in input_list if condition]
|
示例:
1 2 3
| names = ['Bob','Tom','alice','Jerry','Wendy','Smith'] res = [name.upper() for name in names if len(name)>3] print(res)
|
字典推导式
语法:
1 2 3
| { key_expr: value_expr for value in collection } 或 { key_expr: value_expr for value in collection if condition }
|
示例:
1 2 3 4 5 6 7
| user={ "name":"张三", "school":"清华大学", "age":20 } res = {key:str(user[key])+"hello" for key in user} print(res)
|
集合推导式
语法:
1 2 3
| { expression for item in Sequence } 或 { expression for item in Sequence if conditional }
|
示例:
1 2
| a = {x for x in 'abracadabra' if x not in 'abc'} print(a)
|
元组推导式
语法:
1 2 3
| (expression for item in Sequence ) 或 (expression for item in Sequence if conditional )
|
示例:
1 2 3
| a = (x for x in range(1,10)) print(a) print(tuple(a))
|