采集参数
星号只在定义函数(允许使用不定数目的参数)或者调用时才有用
星号的意思就是,收集多余的位置参数,如果不提供收集的元素,params 就是个空元祖
一颗星的采集参数
def print_params(*params): print(params) def print_params_2(title,*params): print(title) print(params) def in_the_middle(x,*y,z): print(x,y,z)
两颗星的采集参数
处理关键字参数的 “收集” 操作,返回的是字典而不是元祖
def print_params_3(**params): print(params)
参数采集逆过程:
**用来返回字典
def helloc(greeting='hello',name='world'): print('{},{}!'.format(greeting,name))
案例
上一节的使用字典存储查找人名
可以将参数改为采集参数
改为采集参数后,函数的使用将更加灵活
def init(data): data['first'] = {} data['middle'] = {} data['last'] = {} def lookup(data, label, name): return data[label].get(name) def store(data, *full_names): for full_name in full_names: names = full_name.split() if len(names) == 2: names.insert(1, '') labels = 'first', 'middle', 'last' for label, name in zip(labels, names): people = lookup(data, label, name) if people: people.append(full_name) else: data[label][name] = [full_name]