上一篇文章為:→1.3.4內建屬性
內建函數
Build-in Function,啟動python解釋器谨读,輸入dir(__builtins__)
, 可以看到很多python解釋器啟動后默認加載的屬性和函數,這些函數稱之為內建函數坛吁, 這些函數因為在編程時使用較多劳殖,cpython解釋器用c語言實現了這些函數,啟動解釋器 時默認加載拨脉。
這些函數數量眾多闷尿,不宜記憶,開發(fā)時不是都用到的女坑,待用到時再help(function), 查看如何使用填具,或結合百度查詢即可,在這里介紹些常用的內建函數匆骗。
range
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
- start:計數從start開始劳景。默認是從0開始。例如range(5)等價于range(0碉就, 5);
- stop:到stop結束盟广,但不包括stop.例如:range(0, 5) 是[0, 1, 2, 3, 4]沒有5
- step:每次跳躍的間距瓮钥,默認為1筋量。例如:range(0烹吵, 5) 等價于 range(0, 5, 1)
python2中range返回列表,python3中range返回一個迭代值桨武。如果想得到列表,可通過list函數
a = range(5)
list(a)
創(chuàng)建列表的另外一種方法
In [21]: testList = [x+2 for x in range(5)]
In [22]: testList
Out[22]: [2, 3, 4, 5, 6]
map函數
map函數會根據提供的函數對指定序列做映射
map(...)
map(function, sequence[, sequence, ...]) -> list
- function:是一個函數
- sequence:是一個或多個序列,取決于function需要幾個參數
- 返回值是一個list
參數序列中的每一個元素分別調用function函數肋拔,返回包含每次function函數返回值的list。
#函數需要一個參數
map(lambda x: x*x, [1, 2, 3])
#結果為:[1, 4, 9]
#函數需要兩個參數
map(lambda x, y: x+y, [1, 2, 3], [4, 5, 6])
#結果為:[5, 7, 9]
def f1( x, y ):
return (x,y)
l1 = [ 0, 1, 2, 3, 4, 5, 6 ]
l2 = [ 'Sun', 'M', 'T', 'W', 'T', 'F', 'S' ]
l3 = map( f1, l1, l2 )
print(list(l3))
#結果為:[(0, 'Sun'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5, 'F'), (6, 'S')]
filter函數
filter函數會對指定序列執(zhí)行過濾操作
filter(...)
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
- function:接受一個參數呀酸,返回布爾值True或False
- sequence:序列可以是str凉蜂,tuple,list
filter函數會對序列參數sequence中的每個元素調用function函數性誉,最后返回的結果包含調用結果為True的元素窿吩。
返回值的類型和參數sequence的類型相同
filter(lambda x: x%2, [1, 2, 3, 4])
[1, 3]
filter(None, "she")
'she'
reduce函數
reduce函數,reduce函數會對參數序列中元素進行累積
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
- function:該函數有兩個參數
- sequence:序列可以是str错览,tuple纫雁,list
- initial:固定初始值
reduce依次從sequence中取一個元素,和上一次調用function的結果做參數再次調用function倾哺。 第一次調用function時轧邪,如果提供initial參數,會以sequence中的第一個元素和initial 作為參數調用function悼粮,否則會以序列sequence中的前兩個元素做參數調用function闲勺。 注意function函數不能為None曾棕。
reduce(lambda x, y: x+y, [1,2,3,4])
10
reduce(lambda x, y: x+y, [1,2,3,4], 5)
15
reduce(lambda x, y: x+y, ['aa', 'bb', 'cc'], 'dd')
'ddaabbcc'
在Python3里,reduce函數已經被從全局名字空間里移除了, 它現在被放置在fucntools模塊里用的話要先引入:
from functools import reduce
sorted函數
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list