python常用函数的用法_python中常用函数整理
1、map
map是python內置的高階函數,它接收一個函數和一個列表,函數依次作用在列表的每個元素上,返回一個可迭代map對象。
class map(object):""" map(func, *iterables) --> map objectMake an iterator that computes the functionusing arguments fromeach of the iterables. Stops when the shortest iterableisexhausted.""" 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 # knowncaseof __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]
li = [1,2,3,4,5]
def add1(x):return x+1res=map(add1, li)
print(res)for i inres:
print(i)
結果:
2
3
4
5
6
2、lambda表達式
是一個表達式,可以創建匿名函數,冒號前是參數,冒號后只能有一個表達式(傳入參數,根據參數表達出一個值)
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
3、Pool
1、多進程,是multiprocessing的核心,它與threading很相似,但對多核CPU的利用率會比threading好的多
2、可以允許放在Python程序內部編寫的函數中,該Process對象與Thread對象的用法相同,擁有is_alive()、join([timeout])、run()、start()、terminate()等方法
3、multiprocessing包中也有Lock/Event/Semaphore/Condition類,用來同步進程
傳統的執行多個函數的例子
import time
def do_proc(n): # 返回平方值
time.sleep(1)return n*nif __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
49execute timeis 8.002938985824585
使用多進程執行函數
import timefrommultiprocessing import Pool
def do_proc(n): # 返回平方值
time.sleep(n)
print(n)return n*nif __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 timeis 3.3244528770446777
查看任務管理器:
4、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)
總結
以上是生活随笔為你收集整理的python常用函数的用法_python中常用函数整理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java todo error_java
- 下一篇: python中pop用法_Python