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

assert

• assert <condition>
• assert <condition>, <error message>

```def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)

mark1 = []
print("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]
print("Average of mark2:",avg(mark2))

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

```Average of mark2: 78.0
AssertionError: List is empty.```

map

```items = [1, 2, 3, 4, 5]
squared = []
for i 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))```

```def multiply(x):
return (x*x)
return (x+x)

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]```

```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 < 0, number_list))
print(less_than_zero)

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

```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

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

243 篇文章62 人订阅

0 条评论

## 相关文章

9040

21260

### 【JAVA零基础入门系列】Day8 Java的控制流程

什么是控制流程？简单来说就是控制程序运行逻辑的，因为程序一般而言不会直接一步运行到底，而是需要加上一些判断，一些循环等等。举个栗子，就好比你准备出门买个苹果...

245100

20460

### Python入门基础连载（2）数据结构

Python数据结构包括了列表（list），元组（tuple），字典（dict）和集合（set），这些也都可以称之为容器，下面Cooldog就和大家一起学习一下...

20770

33390

9210

19150

39040

13610