python中經常使用函數整理

  一、mappython

    map是python內置的高階函數,它接收一個函數和一個列表,函數依次做用在列表的每一個元素上,返回一個可迭代map對象。app

class map(object):
    """
    map(func, *iterables) --> map object
    
    Make an iterator that computes the function using arguments from
    each of the iterables.  Stops when the shortest iterable is exhausted.
    """
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

  用法舉例 :  將列表li中的數值都加1,  li = [1,2,3,4,5]dom

li = [1,2,3,4,5]

def add1(x):
    return x+1

res = map(add1, li)
print(res)
for i in res: print(i) 結果: <map object at 0x00000042B4E6D4E0> 2 3 4 5 6

 

  二、lambda表達式函數

    是一個表達式,能夠建立匿名函數,冒號前是參數,冒號後只能有一個表達式(傳入參數,根據參數表達出一個值)spa

    

nl = lambda x,y:x*y  # 給出x,y參數,計算出x和y的相乘
print(nl(3,5))
pring(-----)
#和map的結合 li
= [1,2,3,4,5] for i in map(lambda x:x*2, li): print(i) 結果: 15 ----- 2 4 6 8 10

  三、Poolrest

    一、多進程,是multiprocessing的核心,它與threading很類似,但對多核CPU的利用率會比threading好的多code

    二、能夠容許放在Python程序內部編寫的函數中,該Process對象與Thread對象的用法相同,擁有is_alive()、join([timeout])、run()、start()、terminate()等方法orm

    三、multiprocessing包中也有Lock/Event/Semaphore/Condition類,用來同步進程對象

  傳統的執行多個函數的例子blog

import time

def do_proc(n):  # 返回平方值
    time.sleep(1)
    return n*n

if __name__ == '__main__':
    start = time.time()
    for p in range(8):
        print(do_proc(p))  # 循環執行8個函數
    print("execute time is " ,time.time()-start)

結果:
0
1
4
9
16
25
36
49
execute time is  8.002938985824585

  使用多進程執行函數

import time
from multiprocessing import Pool

def do_proc(n):  # 返回平方值
    time.sleep(n)
    print(n)
    return n*n

if __name__ == '__main__':
    pool = Pool(3)  # 池中最多隻能放三個任務
    start = time.time()
    p1 = pool.map(do_proc, range(8))  # 跟python的map用法類似(map連續生成8個任務的同時依次傳給pool,pool依次調起池中的任務,執行完的任務從池中剔除)
    pool.close()  # 關閉進程池
    pool.join()  # 等待全部進程(8個進程)的結束
    print(p1)
    print("execute time is ", time.time() - start)

結果:
0
1
2
3
4
5
6
7
[0, 1, 4, 9, 16, 25, 36, 49]
execute time is  3.3244528770446777

   查看任務管理器:

   四、random

import random

print(random.random())  # 生成一個0-1隨機小數
print(random.uniform(10,20))  # 指定範圍隨機選擇一個小數
print(random.randint(10,20))  # 指定範圍內隨機選擇一個整數
print(random.randrange(0,90,2))  # 指定範圍內選擇一個隨機偶數
print(random.choice('abcdefg'))  # 指定字符串中隨機選擇一個字符
print(random.sample('abcdefgh'),2)  # 指定字符串內隨機選擇2個字符
print(random.choice(['app','pear','ora']))  # 指定列表內隨機選擇一個值
itmes = [1,2,3,4,5,6,7,8]  # 將列表表洗牌
random.shuffle(itmes)
print(itmes)
相關文章
相關標籤/搜索