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

assert

• assert <condition>

• assert <condition>, <error message>

第一种

def avg( marks ):
assert
len ( marks ) !=

return sum( marks )/ len ( marks )

mark1 = []
print ( "Average of mark1:" ,avg(mark1))

结果为

AssertionError

第二种

def avg( marks ):
assert
len ( marks ) != , "List is empty."

return sum( 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: List
is empty .

map

很多时候，我们对一个list里的数据进行同一种操作，比如：

items = [ 1 , 2 , 3 , 4 , 5 ]
squared = []
for i in item s:
squared.
append (i** 2 )

这个时候，就可以用map操作，格式为：

map(function_to_apply, list_input)

具体操作为

items = [ 1 , 2 , 3 , 4 , 5 ]
squared = list(map(lambda x: x** 2 , items))

当然list里可以放函数

def multiply (x):

return (x*x)
def add (x):

return (x+x)

funcs = [multiply, add]
for i in range( 5 ):
value = list(map(
lambda x: x(i), funcs))
print(value)

# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]

当然也可以进行str2id操作

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 (lambda x : x < , number_list))
print (less_than_zero)

# Outpu
t: [- 5 , - 4 , - 3 , - 2 , - 1 ]

这个可以用在神经网络中是否对部分网络进行fine-tune

if self. args .fine_tune is False:
parameters =
filter (lambda p : p .requires_grad, model.parameters())
else :
parameters = model.parameters()

reduce

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

product = 1
list = [ 1 , 2 , 3 , 4 ]
for num in list :
product = product * num

# product = 24

用了之后

from functools import reduce
product = reduce((
lambda x, y: x * y), [ 1 , 2 , 3 , 4 ])

# Output: 24

IELTS a bit

colossal adj. 巨大的；广大的；庞大的

deposit n. 存款   v. 将钱存入银行

• 博文量
1395
• 访问量
2586419