国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

Python3 filter() 函數(shù)

2019-03-26 10:18 更新

Python3 filter() 函數(shù)

Python3 內置函數(shù) Python3 內置函數(shù)

描述

filter() 函數(shù)用于過濾序列,過濾掉不符合條件的元素,返回一個迭代器對象,如果要轉換為列表,可以使用 list() 來轉換。

該接收兩個參數(shù),第一個為函數(shù),第二個為序列,序列的每個元素作為參數(shù)傳遞給函數(shù)進行判,然后返回 True 或 False,最后將返回 True 的元素放到新列表中。

語法

以下是 filter() 方法的語法:

filter(function, iterable)

參數(shù)

  • function -- 判斷函數(shù)。
  • iterable -- 可迭代對象。

返回值

返回一個迭代器對象

實例

以下展示了使用 filter 函數(shù)的實例:

過濾出列表中的所有奇數(shù):

#!/usr/bin/python3
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)

輸出結果 :

[1, 3, 5, 7, 9]

過濾出1~100中平方根是整數(shù)的數(shù):

#!/usr/bin/python3
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)

輸出結果 :

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Python3 內置函數(shù) Python3 內置函數(shù)


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號