天天看点

python学习之序列推导式与常用内置高级函数和模块关于推导式序列推导式常用内置高级函数常用高效的内置模块命令行常用函数

关于推导式

推导式,可以看作是一种 “快捷方式”,可以便捷的建立诸如列表、字典等序列数据,在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>}