1.python包管理
安装:pip install xxx, conda install xxx
卸载:pip uninstall xxx, conda uninstall xxx
升级:pip install -upgrade xxx,conda update xxx
详细用法:https://pip.pypa.io/en/stable/reference/
2. .ipynb文件打开
3.python技巧
(1)条件表达式
=
(2)列表推导式
[exp for item in collection if condition] if condation可有可无
=
(3)字典推导式
{exp for item in collection if condition}
运行结果:
4. python 常用容器类型
[] 列表 Lists
{} 集合 sets 里面的元素不能重复,元素之间用逗号隔开
{} 字典 dict 无序 键值对
() 元组 tuple 值不可变
(1)列表
# 列表定义 L = [1,2,'a',4,'b'] print(type(L)) print('修改前:',L) # 修改列表里面的内容 L[0] =3 L[1] = 'C' print('修改后:',L) # 末尾添加元素 L.append(6) print('添加后:', L) # 遍历列表 print('遍历列表(for循环):') for i in L: print(i) # 通过索引遍历列表 print('遍历列表(while循环):') i= 0 while i != len(L): print(L[i]) i += 1 # 列表合并 print('列表合并(+):',[1,2]+[3,4]) # 列表重复 print('列表重复(*)',[1,2]*3) # 判断元素是否在列表中 print('判断元素存在(in):',L in [1,2]) print('判断元素存在(in):',L in [3,'C']) (2)集合
# 集合创建 my_set = {1,2,3} print(my_set) print('添加单个元素:') my_set.add(4) print('添加4', my_set) print('添加多个元素:') my_set.update([4, 5, 6]) print(my_set)
(3)字典
# 字典创建 d = {'百度':'http://www.baidu.com/', '淘宝':'http://www.taobao.com/', '阿里巴巴':'http://www.alibaba.com/'} print('通过key获取value:',d['阿里巴巴']) # 遍历key print('遍历key(for 循环):') for key in d.keys(): print(key) # 遍历value print('遍历value(for)循环:') for value in d.values(): print(value) # 遍历item print('遍历item:') for key, value in d.items(): print(key+ ':'+ value) # format格式输出 print('format格式输出:') for key, value in d.items(): print('{}的网址是{}'.format(key,value))
(4)元组
# 创建元组 tuple = (1,'a',2,'b') print(type(tuple)) # 元组的内容不能修改,否则会报错 # tuple[0]=3 # 遍历元组 print('遍历元组(for循环):') for item in tuple: print(tuple) # 通过索引遍历元组 i= 0 while i != len(tuple): print(tuple[i]) i += 1 # 解包 unpack 5. counter 类似于数学中的多重集
import collections cl = collections.Counter(['a','b','c','a','b','c']) c2 = collections.Counter({'a':2, 'b':3, 'c':1}) c3 = collections.Counter(a=2,b=3,c=1) print(cl) print(c2) print(c3) # 更新内容update(),是加法,不是替换 cl.update({'a':4,'c':1, 'd':4}) print(cl) # 访问内容 print('a=',cl['a']) print('b=',cl['b']) # 对比和dict的区别 # Counter中如果不存在key值,会返回0,dict会报错 print('e=',cl['e']) # elements()方法返回所有元素 for element in cl.elements(): print(element) # most_common()方法,返回前n多的数据 n = cl.most_common(2) print(n)
import collections # 统计每个字母出现的次数 s = 'chinadoop' # 使用counter print(collections.Counter(s)) 6.defaultdict
在python中如果访问字典里不存在的键,会出现报错。有些时候,字典中每个键都存在默认值很方便。
defaultdict是python内建dict类的一个子类,第一个参数为default_factory属性提供初始值,默认为None。他覆盖一个方法并添加一个可写实列变量。功能与dict相同,但会为一个不存在的键提供默认值,从而避免报错异常。
7.map()函数,可用于数据清洗
import collections # 统计每个字母出现的次数 s = 'chinadoop' # 使用counter print(collections.Counter(s))
8.lambda函数
返回值是func类型,可结合map()完成数据清洗操作
my_func = lambda a,b,c: a * b print(my_func(1,2,3)) # 结合map print('lambda结合map') L1 = [1,3,5,7,9] L2 = [2,4,6,8,10] result = map(lambda x,y: x*2+y, L1,L2) print(list(result))