Python 內(nèi)置函數(shù)

幾個常用的內(nèi)置函數(shù)

1. filter 過濾函數(shù)

>>> def is_str(factor):
...     return isinstance(factor, str)
...
>>> test_lines = [1, 2, 3, 'name', 'age', 4, 'sex']
>>> list(filter(is_str, test_lines))
['name', 'age', 'sex']
>>>

下面的列表表達式實現(xiàn)同樣的功能:

>>> [x for x in test_lines if isinstance(x, str)]
['name', 'age', 'sex']
>>>

2. zip 拉鏈函數(shù)(姑且這么叫。。。)

>>> info = ['name', 'age', 'sex']
>>> attr = ['eclipse', 18, 'M']
>>> out = zip(info, attr)
>>> out
<zip object at 0x0000025519874048>
>>> for key, value in out:
...     print("%s: %s" %(key, value))
...
name: eclipse
age: 18
sex: M
>>>

組合的兩個列表或者元組的長度不同,以最短的那個截止:

>>> aa = ['a', 'b', 'c', 'd']
>>> bb = [1, 2, 3, 4, 5]
>>> for k, v in zip(aa, bb):
...     print("%s: %s" %(k, v))
...
a: 1
b: 2
c: 3
d: 4
>>>

3. lambda 匿名函數(shù)

>>> ff = lambda x, y: x + y
>>> print(ff(2, 3))
5
>>>

對于那些可以傳入key的內(nèi)置函數(shù)來說,可以用lambda去篩選,比如我要取出價格最高的水果:

>>> dic = {'apple': 109, 'orange': 88, 'banana': 98, 'peach': 111}
>>> print(max(dic, key = lambda k: dic[k]))
peach
>>>

4. map 函數(shù),我覺得這個函數(shù)就是映射

>>> list_ = [1, 3, 5, 7, 9]
>>> def square(x):
...     return x**2
...
>>> list(map(square, list_))
[1, 9, 25, 49, 81]
>>>

5. 兩個高級的用法,說是某個公司的面試題

(('a'), ('b'))(('c'), ('d'))組合成[{'a': 'c', 'b': 'd'}]

>>> ret = zip((('a'), ('b')), (('c'), ('d')))
>>> out = map(lambda tup: {tup[0]: tup[1]}, ret)
>>> list(out)
[{'a': 'c'}, {'b': 'd'}]
>>>

>>> def multipliers():
...     return (lambda x: i * x for i in range(4))
...
>>> print([m(2) for m in multipliers()])
[0, 2, 4, 6]
>>>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容