關于推導式
推導式,可以看作是一種 “快捷方式”,可以便捷的建立諸如清單、字典等序列資料,在python2 和 python 3 中,對于資料類型界定是有差異的,對于資料類型歸屬的差異:以 range為例:
a=range(10)
# python2中
>>> type(a)
<type 'list'>
# python3中
>>> type(a)
<class 'range'>
在python2中,xrange屬于生成器,其記憶體占用少,是以,在python2中盡量使用xrange,少用range,需要注意的是在python3中,xrange已經被去除,隻剩range。
序列推導式
涉及的序列:集合,清單,字典和元組。
清單推導式:
b = [i for i in range(10)]
(生成器)推導式:
b = (i for i in range(10))
集合推導式:
b = {i for i in range(10)}
字典推導式:
b = {i:(i**2) for i in range(10)}
常用内置進階函數
這裡主要介紹 map,reduce,filter,以及經常使用的匿名函數 lambda 。
map 作用是将函數方法作用到序列對象:
def metd(a):
return a**3
# python2 中, b為清單,python3中,b為map對象,需要轉化為清單 list(b)
b = map(metd,[1,2,3])
reduce 類似疊代器,按照函數設定的方法從序列開頭逐漸執行到序列末尾。
需要注意的是,該函數隻在python2中内置可用。在Python 3中,reduce 函數放置在fucntools 子產品裡,需要導入之後才能使用。
# python 3 中需要添加下面一行代碼
# from functools import reduce
x = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # x = 15
# 執行過程:逐漸求和
# x = ( ( ( ( 1 + 2 ) + 3 ) + 4 ) + 5 )
filter 的作用是執行資料篩選,傳回序列中滿足條件的元素。
def gl(x):
if x%2 == 0:
return True
else:
return False
# python2 中, y為清單,python3中,y為filter對象,需要轉化為清單 list(y)
y = filter(gl, [1,2,4,6,7,9,21])
常用高效的内置子產品
1、itertools子產品
itertools 子產品是處理疊代器的工具集合,在python2中,itertools 子產品中包含izip,而在python3中則可用直接調用内置zip類,二者的用法相同,下面的例子運作于python3.7環境。
from itertools import dropwhile,groupby
# 合并清單,傳回元組疊代器
for i in zip([1, 2], [ a , b]):
print(i)
# ( a , 1)
# ( b , 2)
# 條件過濾,類似filter函數,但是既傳回初次為false的元素又傳回所有元素。
>>> def check_for_drop(x):
... print('Checking:', x)
... return (x > 4)
...
>>> for i in dropwhile(check_for_drop, [2, 4, 6]):
... print('Result:', i)
...
Checking: 2
Result: 2
Result: 4
Result: 6
# 傳回分組元素
a = sorted([1, 2, 1, 3, 1, 2])
# a = [1, 1, 1, 2, 2, 3]
for key, value in groupby(a):
print( ( key, list(value) ), end='\n')
# (1, [1, 1, 1])
# (2, [2, 2])
# (3, [3])
2、collections子產品
collections 内置子產品是很高效的子產品之一,其内部包含Counter、OrderedDict、UserList等常用類。
import collections
>>> dir(collections)
['ChainMap', 'Counter', 'OrderedDict', 'UserDict', 'UserList', 'UserString', '_Link', '_OrderedDictItemsView', '_OrderedDictKeysView', '_OrderedDictValuesView', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__getattr__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_chain', '_collections_abc', '_count_elements', '_eq', '_heapq', '_iskeyword', '_itemgetter', '_nt_itemgetters', '_proxy', '_recursive_repr', '_repeat', '_starmap', '_sys', 'abc', 'defaultdict', 'deque', 'namedtuple']
# 以字元統計為例,說明 Counter類的用法
x = 'sfdsfferwre345665u56u67firegiegjtir2r49r94t58kgkdgjhrhdhsg'
y = collections.Counter(x)
#檢視統計結果
>>> y.most_common()
[('r', 7), ('g', 5), ('f', 4), ('e', 4), ('5', 4), ('6', 4), ('s', 3), ('d', 3), ('4', 3), ('i', 3), ('h', 3), ('u', 2), ('j', 2), ('t', 2), ('9', 2), ('k', 2), ('w', 1), ('3', 1), ('7', 1), ('2', 1), ('8', 1)]
# 檢視出現次數最多的3個字元
>>> y.most_common(3)
[('r', 7), ('g', 5), ('f', 4)]
指令行常用函數
這裡的指令行,指的是python互動指令行,以 python 3.7為例。
C:\Users\Administrator>python37
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
1、help函數
help 函數通常用于檢視 目标 如内置的和導入的各種 類、方法的使用幫助,類似于linux下面的man指令,作用 與 調用pycharm檢視源碼類似。
例如下面函數 使用說明(3個單引号包圍的内容):
# 定義函數
>>> def test(a,b):
... '''
... a: ip address
... b: int, port
... '''
... pass
...
# 調用help, 查詢test函數的使用幫助
>>> help(test)
Help on function test in module __main__:
test(a, b)
a: ip address
b: int, port
2、dir函數
dir函數通常用于檢視 目前環境已經存在的子產品、方法、屬性等,傳回的是一個清單,與globals、locals類似,但是後面兩個傳回的都是鍵值對型的字典,内容更為豐富。
# 進入指令行後初始狀态
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
# 導入子產品中所有組成元素
from itertools import *
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']
# 此時執行locals的結果
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'tee': <built-in function tee>, 'accumulate': <class 'itertools.accumulate'>, 'combinations': <class 'itertools.combinations'>, 'combinations_with_replacement': <class 'itertools.combinations_with_replacement'>, 'cycle': <class 'itertools.cycle'>, 'dropwhile': <class 'itertools.dropwhile'>, 'takewhile': <class 'itertools.takewhile'>, 'islice': <class 'itertools.islice'>, 'starmap': <class 'itertools.starmap'>, 'chain': <class 'itertools.chain'>, 'compress': <class 'itertools.compress'>, 'filterfalse': <class 'itertools.filterfalse'>, 'count': <class 'itertools.count'>, 'zip_longest': <class 'itertools.zip_longest'>, 'permutations': <class 'itertools.permutations'>, 'product': <class 'itertools.product'>, 'repeat': <class 'itertools.repeat'>, 'groupby': <class 'itertools.groupby'>, 'test': <function test at 0x00000182D2EDC1E0>}
# globals 執行結果
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'tee': <built-in function tee>, 'accumulate': <class 'itertools.accumulate'>, 'combinations': <class 'itertools.combinations'>, 'combinations_with_replacement': <class 'itertools.combinations_with_replacement'>, 'cycle': <class 'itertools.cycle'>, 'dropwhile': <class 'itertools.dropwhile'>, 'takewhile': <class 'itertools.takewhile'>, 'islice': <class 'itertools.islice'>, 'starmap': <class 'itertools.starmap'>, 'chain': <class 'itertools.chain'>, 'compress': <class 'itertools.compress'>, 'filterfalse': <class 'itertools.filterfalse'>, 'count': <class 'itertools.count'>, 'zip_longest': <class 'itertools.zip_longest'>, 'permutations': <class 'itertools.permutations'>, 'product': <class 'itertools.product'>, 'repeat': <class 'itertools.repeat'>, 'groupby': <class 'itertools.groupby'>, 'test': <function test at 0x00000182D2EDC1E0>}
通過比較三者的len方法結果發現,長度(元素個數)相同,均為26。
globals與locals的差別:
locals() 函數會以字典類型傳回目前位置的所有局部變量;
globals() 函數會以字典類型傳回所有全局變量;
# 初始狀态
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>>
>>> z=2
>>>def runs(arg):
... z = 1
... print(locals())
... print(globals())
...
>>> runs(333)
{'arg': 333, 'z': 1}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'z': 2, 'runs': <function runs at 0x0000029BC802C1E0>}