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))