介绍4个大神常用而你不常用的python函数
介绍4个大神常用而你不常用的python函数
https://mp.weixin.qq.com/s/C2nw4JShmj1FlLeDy0IeRA
今天总共说下四个函数: assert ,map,filter,reduce 。
assert
俗称 断言!就是说断言一件事,如果是真,程序继续进行;如果是假,则报错。
怎么用捏?
两种用法
assert
assert
, 第一种
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: 24IELTS a bit
colossal adj. 巨大的;广大的;庞大的
deposit n. 存款 v. 将钱存入银行