介绍4个大神常用而你不常用的python函数
阅读大概需要3分钟跟随小博主,每天进步一丢丢
今天总共说下四个函数:assert,map,filter,reduce。
assert
俗称 断言!就是说断言一件事,如果是真,程序继续进行;如果是假,则报错。
怎么用捏?
两种用法
- assert <condition>
- assert <condition>, <error message>
第一种
def avg(
marks):
assert
len(
marks) !=
0return
sum(
marks)/
len(
marks)
mark1 = []
(
"Average of mark1:",avg(mark1))
结果为
AssertionError
第二种
def avg(
marks):
assert
len(
marks) !=
0,
"List is empty."return
sum(
marks)/
len(
marks)
mark2 = [
55,
88,
78,
90,
79]
(
"Average of mark2:",avg(mark2))
mark1 = []
(
"Average of mark1:",avg(mark1))
结果为
Average of mark2:
78.0AssertionError: List
isempty.
map
很多时候,我们对一个list里的数据进行同一种操作,比如:
items
for
= [
1,
2,
3,
4,
5]
squared = []
for
i in item
s: squared.
append(i**
2)
这个时候,就可以用map操作,格式为:
map(function_to_apply, list_input)
具体操作为
items
squared
= [
1,
2,
3,
4,
5]
squared
= list(map(lambda x: x**
2, items))
当然list里可以放函数
return
(x*x)
defadd(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
print
= [
'5',
'2',
'3',
'4',
'5']
(
list(
map(
int,
a)))
# [
5,
2,
3,
4,
5]
filter
filter函数就是对于给定的条件进行筛选,过滤。
number_list =
range(-
5,
5)
less_than_zero =
list(
filter(lambda
x:
x <
0, number_list))
(less_than_zero)
# Outpu
t: [-
5, -
4, -
3, -
2, -
1]
这个可以用在神经网络中是否对部分网络进行fine-tune
if
else
self.
args.fine_tune
is False:
parameters =
filter(lambda
p:
p.requires_grad, model.parameters())
else
:
parameters = model.parameters()
reduce
reduce就是累计上次的结果,用在当前操作上。比如不用reduce是这样的
product =
1list
= [
1,
2,
3,
4]
for
num in
list:
product = product * num
# product = 24
用了之后
from
# Output: 24
functools
import reduce
product = reduce((
lambda x, y: x * y), [
1,
2,
3,
4])
# Output: 24
IELTS a bit
colossal adj. 巨大的;广大的;庞大的
deposit n. 存款 v. 将钱存入银行
PS:如果觉得文章对您有一丢丢帮助
欢迎点赞与转发!
推荐阅读:
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。