这里是清安,本章来看一些比较实用的基础内容。
本章没有长篇大论,因为没有必要!
直接看代码
变量交换
a = 0 b = 1 temp = a a = b b = temp print(a,b) # 1 0
优化后
a,b = b,a print(a,b) # 1 0
推导式
my_list = [] for i in range(10): my_list.append(i) print(my_list) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
优化后
my_list = [i for i in range(10)] print(my_list) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
同样适用于tuple,dict。
带索引的遍历
my_list = [0,1,2,3,4,5,6,7,8,9] for key,value in zip(range(len(my_list)),my_list): print(key,value)
优化后
my_list = [0,1,2,3,4,5,6,7,8,9] for key,value in enumerate(my_list): print(key,value)
解包
my_list = [0,1,2] a,b,c = my_list print(a,b,c) # 0 1 2
def info(): name,age,sex = '清安','18','男' return name,age,sex a,b,c = info() print(a,b,c) # 清安 18 男
items = [('apple', 2), ('banana', 4), ('orange', 6)] for fruit, num in items: print(f"我有{num}个{fruit}") # 我有2个apple # 我有4个banana # 我有6个orange
字符串拼接
str_ = ['Q','i','n','g','A','n'] s = '' for i in str_: s+=i print(s)
优化后
str_ = ['Q','i','n','g','A','n'] print(''.join(str_)) # QingAn
真假判断
attrs = 0 if attrs == True: print(111) att = 1 if att == None: print(222)
优化后
attrs = 0 if attrs: print(111) att = 1 if not att: print(222)
三目运算
age = 18 if age > 18: print("年龄超过了") else: print("合适")
优化后
age = 18 info = "年龄超过了" if age > 18 else "合适" print(info)
❝此外还有一种写法,各位自行理解
❞
def info(): j = 5 # j = 0 return [i for i in range(j)] or None num = info() print(num)
它的分解式是这样的:
def info(): j = 5 # j = 0 if j > 0: return [i for i in range(j)] else: return None num = info() print(num)