你使用*, **可以自动的对一个list,dict做函数参数,自动的解包
例子:
def draw_point(x, y): # do some magic point_foo = (3, 4) point_bar = {‘y‘: 3, ‘x‘: 2} draw_point(*point_foo) draw_point(**point_bar)
这是一个非常捷径的用法。
NOTE:
请看这两个程序的不同。。。
def cheeseshop(kind, *arguments, **keywords): print "-- Do you have any", kind, "?" print "-- I‘m sorry, we‘re all out of", kind for arg in arguments: print arg print "-" * 40 keys = sorted(keywords.keys()) for kw in keys: print kw, ":", keywords[kw] cheeseshop("Limburger", "It‘s very runny, sir.", "It‘s really very, VERY runny, sir.", shopkeeper=‘Michael Palin‘, client="John Cleese", sketch="Cheese Shop Sketch")
Python不单可以自动解包,也可以自动的形成tuple,dict数据结构作为函数参数。。
时间: 2024-11-01 04:36:20