python函数(2)

python函数中的可变参数

  1. *可变函数
    在函数中被组装成元组
def sum(*numbers):
	total = 0.0
	for number in numbers:
		total += number
	return total
print(sum(100.0, 20.0, 30.0))
print(sum(80.0, 30.0))
  1. **可变参数
    被组装成字典的形式
def show_info(**info):
	print('------show_info------')
	for key, value in info.items():
		print('{0} - {1}'.format(key, value))
	
show_info(name='Tony', age='18', sex=True)
show_info(student_name='Tony', student_no='1000')

函数类型

类型为function
函数返回值可以是函数

def add(a,b):
	return a+b
def sub(a,b):
	return a-b
def calc(opr):
	if opr == '+':
		return add
	else:
		return sub
f1 = calc('+')# f1实际上是add函数,下面同理
f2 = calc('-')
print("10 + 5 = {0}".format(f1(10,5)))
print("10 - 5 = {0}".format(f2(10,5)))

过滤函数filter()

函数参数为:filter(function, iterable)

def f1(x):
	return x > 50
data1 = [60, 15, 91, 28, 98, 50, 7, 80, 99]
filtered = filter(f1, data1)
data2 = list(filtered)
print(data2)

映射函数map()

函数参数为:map(function, iterable, ...)

  • function – 函数
  • iterable – 一个或多个序列

对序列的每一个值使用function所给函数进行映射,返回映射结果(即对每个值进行函数操作)

def f1(x):
	return x * 2
data1 = [60, 15, 91, 28, 98, 50, 7, 80, 99]
mapped = map(f1, data1)
data2 = list(mapped )
print(data2)

Lambda()函数

函数参数为:lambda arguments: expression

  • lambda是 Python 的关键字,用于定义 lambda 函数。
  • arguments 是参数列表,可以包含零个或多个参数,但必须在冒号(:)前指定。
  • expression 是一个表达式,用于计算并返回函数的结果。
def calc(opr):
	if opr == '+':
		return lambda a, b: (a+b)
	else:
		return lambda a, b: (a-b)
f1 = calc('+')# f1实际上是add函数,下面同理
f2 = calc('-')
print("10 + 5 = {0}".format(f1(10,5)))
print("10 - 5 = {0}".format(f2(10,5)))
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值