数据分析中常用的Python技巧
1. 条件表达式 import math # 普通写法 import math def get_log(x): if x > 0: y = math.log(x) else: y = float('nan') return y # 使用条件表达式 x = 5 log_val1 = get_log(x) # 使用条件表达式 log_val2 = math.log(x) if x > 0 else float('nan') print(log_val1) print(log_val2) 2. 列表推导式 print('找出1000内的偶数(for循环):') l1 = [] for i in range(1000): if i % 2 == 0: l1.append(i) print(l1) print('找出1000内的偶数(列表推导式):') l2 = [i for i in range(1000) if i % 2 == 0] print(l2) # list列表 l = [1, 'a', 2, 'b'] print(type(l)) print('修改前:', l) # 修改list的内容 l[0] = 3 print('修改后:', l) # 末尾添加元素 l.append(4) print('添加后:', l) # 遍历list print('遍历list(for循环):'