# *参数,定义任意数量的参数
def avg(*scores):
return sum(scores) / len(scores)
scores = (98,99,80)
#解包传参
res = avg(*scores)
print(res)
# **参数,定义字典表参数
def display(**args):
print(args)
dic = {'name': 'Tom', 'age': 20, 'job': 'dev'}
display(name='Tom', age=20)
display(**dic)
# lambda表达式
f = lambda name: print(name)
f2 = lambda x, y: x + y
f('Tom')
print(f2(10, 20))
# 类似于c#的委托
def hello_chinese(name):
print('你好:', name)
def hello_english(name):
print('hello', name)
while True:
name = input('输入姓名:\n')
if name == 'stop':
break
language = input('请选择语言:\n')
if language == 'c':
# ,实例化一个委托
action = hello_chinese
elif language == 'e':
action = hello_english
elif language == 'j':
action = lambda name: print('(*´▽`)ノノ', name)
action(name)
# 带参数的lambda表达式
f = lambda name, age: print("Hello {},age:{}".format(name, age))
f('Man', 20)
# 类似c#委托,将函数作为参数传递给其他函数
def hello(action, name):
action(name)
def hello_chinese(name):
print('你好', name)
hello(hello_chinese, 'Tom')
hello(lambda name: print('hello', name), 'Tom')
# 列表中的数加固定数
ls = list(range(1, 21))
res = []
def add_number(num):
return num + 5
# 循环
for num in ls:
res.append(num + 5)
# 推导
res = [num + 5 for num in ls]
# map()
# 将l作为参数传递给add_number方法
res = list(map(add_number, ls))
res = list(map(lambda num: num * 2, ls))
print(res)
ls = list(range(1, 21))
def even_number(num):
return num % 2 == 0
# filter(),过滤序列,过滤掉不符合条件的元素,返回可迭代对象。
res = filter(even_number, ls)
print(list(res))
Python基础语法重温第四天
最新推荐文章于 2024-04-29 19:04:15 发布