python3內建函數介紹

零下一度
發布: 2017-07-23 11:29:38
原創
1142 人瀏覽過

在python3 中,filter、map、reduce已經不是內建函數,也就是,python3中三者是class,回傳結果變成了可迭代的物件

1.filter(function,iterable)

透過function篩選條件,去取得iterable中你想要的資料。

from collections import Iterator
test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
f = filter(lambda x: x % 3 == 0, test_list)
# filter 得到的是一个迭代器

print(isinstance(f, Iterator))
f.__next__()

for i in f:
    print(i)

#输出

True
6
9
登入後複製

  

2.map(functioniterable#)

接受一個函數和可迭代物件(如列表等),將函數依序作用於序列的每一個元素,形成一個新的迭代器。

from collections import Iterator


def f(x):
    return 2 * x  # 定义一个函数

t_list = [1, 2, 3, 4, 5]

function = map(f, t_list)

print(isinstance(function, Iterator))
# print(function.__next__())
function.__next__()
for i in function:
    print(i)

#输出
True
4
6
8
10
登入後複製

  

3.reduce(function,iterable)

reduce把一個函數作用在一個可迭代序列,這個函數必須接收兩個參數,reduce把結果繼續和序列的下一個元素做累積計算

reduce函數在python3中已經不屬於build-in了,而是在functools模組下,如需使用,需要從functools模組中引入

from functools import reduce

f = reduce(lambda x, y: x*y, [1, 2, 4])

print(f)

#输出
8
登入後複製

 

4.hex(x)

把一個數字轉為16進位

>>> hex(23)
'0x17'
登入後複製

  

5.range(stop)、range(start,stop,[step])

#產生一個可迭代物件

#
>>> from collections import Iterator
>>> isinstance(range(5),Iterator)
False
>>> from collections import Iterable
>>> isinstance(range(5),Iterable)
True

>>> f.__next__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: &#39;range&#39; object has no attribute &#39;__next__&#39;
>>> for i in f:
...     print(i)
...
0
1
2
3
4

# range(x) 是一个可迭代对象,而不是一个迭代器
登入後複製

  

6. isinstance(object, classinfo)

判斷一個序列是否為可迭代物件或迭代器

 

7 .list([iterable])

把其他序列轉換成一個清單

>>> list((1,2,3,4,5))   #把一个元组转换为一个列表
[1, 2, 3, 4, 5]
登入後複製

  

8.repr(#object )

把程式碼轉成字串對象,沒什麼用,這邊忽略

 

9.slice(stop ),slice(startstop[, step])

序列的切片

#
>>> a = [1,2,3,4,5,6]
>>> a[slice(1,3)]
[2, 3]
>>> a[1:3]
[2, 3]
登入後複製

  

10.sorted(it​​erable[, key][, reverse])

>>> sorted([5,3,2,6,8])
[2, 3, 5, 6, 8]
>>> a = {1:5,6:8,3:6}
>>> sorted(a)  #默认是按key排序
[1, 3, 6]
>>> sorted(a.items())  #按key排序
[(1, 5), (3, 6), (6, 8)]
>>> sorted(a.items(),key = lambda x:x[1])  #按value排序
[(1, 5), (3, 6), (6, 8)]
登入後複製

#  

 11.reverse()

#用於反向清單中元素,此方法沒有傳回值,但是會對清單的元素進行反向排序。

 a = [1,2,4,5,3,7]
 a.reverse()
a
[7, 3, 5, 4, 2, 1]
登入後複製

  

##

以上是python3內建函數介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!