python學習 高階特性

2021-09-12 09:33:55 字數 2484 閱讀 7040

高階函式

可以使用函式作為引數的函式

def f(func):

sorted:對列表排序,有乙個名為key的引數

指定key為abs,根據l的絕對值排序sorted(l,key=abs)

filter:對序列過濾

filter(a,b) a為函式,b為被處理的資料列表,a會對b中的每個元素判斷,結果為真擇保留,否則捨棄

map/reduce

map:map(a,b),a為函式,b為可迭代的物件,a用來處理b引數

def a(i):

return i**2

map(a,b) 對b的物件中每個資料進行求平方的操作

list(map(a,b)) 生成新的列表

reduce(a,b) a處理b,但是是疊加的操作

def a(x,y)

return x+y

reduce(a,b)

python3中 from functools import reduce

lambda :匿名函式

f = lambad x:x*2

f(2) 4

針對二元組列表

list1 = [(『a』,1),(『b』,2)]

sorted 排序

list(sorted(list1,lambda x:x[1])) 根據第二個元素排序

def f(x):

if x[1]>1:

return true

else:

return false

list(filter(f,list1)) 根據第二個元素排序

list(filter(lambda x:x[1]>1,list1))

偏函式—預設引數

from functools import partial

def a(i,m=2):

return i*m

a(4)

a(4,4)

切片

獲取乙個序列(列表或元祖)或者字串中一部分

l = [『a』,』b』,』c』,』d』,』e』,』f』,』g』]

copy = l[:] 複製l

l[:4] [『a』,』b』,』c』,』d』]

l[4:] [『e』,』f』,』g』]

l[2:5] [『c』,』d』,』e』]

l[1:-4] [『b』,』c』]

0 1 2 3 4 5 6

a b c d e f g

-7-6-5-4-3-2 -1

列表解析

列表推導

numbers = [1,2,3,4,5,6,7,8,9,10]

[x for x in numbers if x%2==0] 獲取numbers中的偶數

[x*x for x in numbers] 對numbers中的每個數求平方

字典解析

d = 

d =

元祖拆包

元祖允許左邊的變數依次被元祖的元素賦值

t = (『tom』,12)

a,b = t

a = tom b=12

print(『i』m {},i』m {} years old』.format(*t))

i'm tom,i'm 12 years old

迭代器

可迭代的物件就是能用for迴圈迭代的元素

比如list

for i in list:

print(i)

it = iter(list)

next(it)

呼叫一次輸入乙個內容,直到沒有內容,報錯

it = list.__iter__()

it.__next__()

class test:

def __init__(self,name):

self.name=name

def __iter__(self):

return self

def __next__(self):

self.name+=1

if self.name >12:

raise stopiteration()

return self.name

a = test(1)

a就是乙個迭代器

next(a) 2

next(a) 3

*能被for迴圈訪問的就是可迭代物件,能被next函式獲取下乙個值的就是迭代器

*stopiteration

python學習 基礎 高階特性

高階特性 print list range 1,100,2 切片 切片 字串,物件,陣列都可以使用 print list range 1,100,2 list1 michael sarah tracy bob jack 取陣列前n個元素 0 n 1 取出前3個元素,如果第乙個索引是0,還可以省略 p...

python學習之高階特性

切片 對列表 元組 字串 字典取中間的一部分,在c中一般是通過for迴圈拷貝 memcpy strcat等操作。而python提供了更方便的切片操作符 m n 前閉後開,如果從0取m可以省略 如果只用 就是切整片 也可以從尾端切片 m 前後的閉區間。列表生成式 list range m,n 構造乙個...

Python高階特性

l csx sarah tracy bob jack print l 0 l 1 l 2 輸出 csx sarah tracy l 0 3 輸出 csx sarah tracy 如果第乙個索引是0,還可以省略 print l 2 輸出 bob jack print l 2 1 輸出 bob d fo...