TVP

# 介绍4个大神常用而你不常用的python函数

assert

assert

assert ,

def avg(marks):

assertlen(marks) !=

returnsum(marks)/len(marks)

mark1 = []

print("Average of mark1:",avg(mark1))

AssertionError

def avg(marks):

assertlen(marks) !=,"List is empty."

returnsum(marks)/len(marks)

mark2 = [55,88,78,90,79]

print("Average of mark2:",avg(mark2))

mark1 = []

print("Average of mark1:",avg(mark1))

Average of mark2:78.0

AssertionError: Listisempty.

map

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

squared = []

fori in items:

squared.append(i**2)

map(function_to_apply, list_input)

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

squared= list(map(lambda x: x**2, items))

defmultiply(x):

return(x*x)

return(x+x)

funcs = [multiply, add]

foriinrange(5):

value = list(map(lambdax: x(i), funcs))

print(value)

# Output:

# [0, 0]

# [1, 2]

# [4, 4]

# [9, 6]

# [16, 8]

a= ['5','2','3','4','5']

print(list(map(int,a)))

# [5,2,3,4,5]

filter

filter函数就是对于给定的条件进行筛选，过滤。

number_list =range(-5,5)

less_than_zero =list(filter(lambdax:x

print(less_than_zero)

# Output:[-5, -4, -3, -2, -1]

reduce

reduce就是累计上次的结果，用在当前操作上。比如不用reduce是这样的

product =1

list= [1,2,3,4]

fornum inlist:

product = product * num

# product = 24

fromfunctoolsimportreduce

product = reduce((lambdax, y: x * y), [1,2,3,4])

# Output: 24

IELTS a bit

depositn. 存款 v. 将钱存入银行

PS：如果觉得文章对您有一丢丢帮助

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

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21

2024-04-21