本系列內(nèi)容來源于 廖雪峰的Python教程 點擊查看原文
迭代
dict 的迭代
d = {'a':1,'b':2,'c':3}
#遍歷key
for key in d:
print(key,end=" ")
#遍歷values
for key in d.values():
print(key,end=" ")
#遍歷key values
for k, v in d.items():
print(k,':',v,end=" ")
c b a
3 2 1
c:3 b:2 a:1
列表生成式
形如:[表達式/x for x in range(0,10) 表達式]
[x for x in range(1,11)]
[x*x for in range(1,11)]
[x*x for in range(1,11) if x % 2 == 2]
#兩層循環(huán)
>>> [m+n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
#獲取當前目錄
>>> import os
>>> [d for d in os.listdir('.')]
['Alice', 'AliceRobot', 'Android學習.txt', 'Bayes-master', 'CloudReader-master', 'd.jpg', 'desktop.ini', 'fnlp', 'fnlp-master', 'fnlp.zip', 'HttpClient.jar', 'learngit', 'NDK', 'RobotService.zip', 'textt.py']
>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L if isinstance(s,str)]
['hello', 'world', 'apple']
生成器
列表生成器
把列表生成式的[] 換成()
通過next()去輸出一次的結(jié)果
>>> g = (x for x in range(10))
>>> g
<generator object <genexpr> at 0x0000016D28CBC728>
>>> next(g)
0
>>> next(g)
1
>>> for x in g:
print(x,end=" ")
2 3 4 5 6 7 8 9
生成器函數(shù)
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
在每次調(diào)用next()的時候執(zhí)行,遇到y(tǒng)ield語句返回,再次執(zhí)行時從上次返回的yield語句處繼續(xù)執(zhí)行。
高級函數(shù)
變量指向函數(shù)
>>> f = abs
>>> f
<built-in function abs>
>>> f = abs
>>> f(-10)
10
map/reduce
map()函數(shù)接收兩個參數(shù),一個是函數(shù),一個是Iterable,map將傳入的函數(shù)依次作用到序列的每個元素,并把結(jié)果作為新的Iterator返回
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce把一個函數(shù)作用在一個序列[x1, x2, x3, ...]上,這個函數(shù)必須接收兩個參數(shù),reduce把結(jié)果繼續(xù)和序列的下一個元素做累積計算
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
filter
filter()也接收一個函數(shù)和一個序列
filter()把傳入的函數(shù)依次作用于每個元素,然后根據(jù)返回值是True還是False決定保留還是丟棄該元素。
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
sorted
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
根據(jù)key自定義排序
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
忽略大小寫,并反向排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
返回函數(shù)
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f()
25
匿名函數(shù)(lambda)
lambda x: x * x
相當于
def f(x):
return x * x
裝飾器 請自行百度
偏函數(shù)
在 python的functools模塊等
int("10000",base=2) #10000二進制 轉(zhuǎn)換為十進制 base默認為10
創(chuàng)建 偏函數(shù)
>>> import functools
>>> int2 = functools.partial(int,base=2)
>>> int2('100000')
32
>>> int2('101001')
41
>>>