TVP

# 【Python】14.清尘

——《楚辞·远游》

map（映射）函数

Python的内置函数map是比较有用的一个高阶函数，它对数组（或我们称为iterable（可遍历对象）的类似对象）进行一些操作。

return x + 5

nums = [11, 22, 33, 44, 55]

print(result)

>>>

[16, 27, 38, 49, 60]

>>>

nums = [11, 22, 33, 44, 55]

result = list(map(lambdax: x+5, nums))

print(result)

>>>

[16, 27, 38, 49, 60]

>>>

filter（过滤器）函数

nums = [11, 22, 33, 44, 55]

res = list(filter(lambdax: x%2==0, nums))

print(res)

>>>

[22, 44]

>>>

nums = [1, 2, 5, 8, 3, 0, 7]

res = list( _____ (lambda x: x _____ 5, _____ ))

print(res)

filter

nums = [1, 2, 5, 8, 3, 0, 7]

res = list(filter (lambda x: x

print(res)

generator（系列值生成器）

generator是一种可遍历对象，类似于数组或元组。

defcountdown():

i=5

while i > 0:

yieldi

i -= 1

for i in countdown():

print(i)

definfinite_sevens():

while True:

yield7

for i in infinite_sevens():

print(i)

>>>

7

7

7

7

...

_____ get_primes():

num = 2

while True:

if is_prime(num):

_____ _____

num _____ 1

def yield num+=

def get_primes():

num = 2

while True:

if is_prime(num):

yield num

num += 1

defnumbers(x):

for i in range(x):

if i % 2 == 0:

yieldi

print(list(numbers(11)))

>>>

[0, 2, 4, 6, 8, 10]

>>>

def make_word():

word = ""

for ch in "spam":

word +=ch

yield word

print(list(make_word()))

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20180816G02OWZ00?refer=cp_1026
• 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 cloudcommunity@tencent.com 删除。

2023-01-27

2023-01-27

2023-01-27

2023-01-27

2023-01-27

2023-01-27

2023-01-27

2023-01-27

2023-01-27

2023-01-27

2023-01-27

10元无门槛代金券