介绍4个大神常用而你不常用的python函数--assert，map，filter，reduce

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