变量交换
# Unrecommendedtemp = aa = bb = temp# Recommendeda, b = b, a
链式比较
# Unrecommendedif grade > 60 and grade < 90: print("passed")# Recommendedif 60 < grade < 90: print("passed")
三目运算 Python 不支持三目运算符 ? :
# Unrecommendedif torch.cuda.is_available(): device = torch.device("cuda")else: device = torch.device("cpu")# Recommendeddevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")
文件操作
# Unrecommendedf = open('file.txt', 'w')f.write("test")f.close() # Recommendedwith open('file.txt', 'w') as f: f.write('test')
字符串拼接
# Unrecommendedlist = ['1','2','3','4','5']str = ""for item in list: str += item# Recommendedstr = ''.join(list)
列表推导 生成列表
# Unrecommendedlist = []for i in range(5): list.append(i) # Recommended: List Comprehensionlist = [i for i in range(5)]
过滤列表元素
# Unrecommendedodd = []for i in list: if i % 2 != 0: odd.append(i)# Recommendedodd = [i for i in list if i % 2 != 0]# orodd = filter(lambda x: x % 2 != 0, list)
内置函数 map Python 2.x 直接返回列表
>>> def square(x) : ..、 return x ** 2>>> map(square, [1, 2, 3, 4, 5]) [1, 4, 9, 16, 25]>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) [1, 4, 9, 16, 25]
Python 3.x 返回迭代器,使用 list() 转换为列表
>>> def square(x): ..、 return x ** 2>>> map(square, [1, 2, 3, 4, 5])
装饰器
def funA(fun): print("this is A") fun() return "this is result"@funAdef funB(): print("this is B")if __name__ == "__main__": print(funB)# this is A# this is B# this is result
最后祝大家天天进步!!学习Python最重要的就是心态。我们在学习过程中必然会遇到很多难题,可能自己想破脑袋都无法解决。这都是正常的,千万别急着否定自己,怀疑自己。如果大家在刚开始学习中遇到困难,想找一个python学习交流环境,可以 加入我们,领取学习资料、一起讨论。