Python * 和** 解压赋值操作符使用

1. 解压赋值:

   * tuple  ** dict

>>> p = [1,2]
>>> x,y = p
>>> x,y
(1, 2)
>>> record = [
	('bar',1,2),
	('foo','hello'),
	('bar', 3, 4),
]
>>> def do_bar(x,y):
	print('bar',x,y)

	
>>> def do_foo(s):
	print('foo',s)


>>> for name,*args in record:
	if name == 'bar':
		do_bar(*args)  # 解压赋值
	elif name == 'foo':
		do_foo(*args)

		
bar 1 2
foo hello
bar 3 4


使用占位符:

>>> data = ['bar',1,2,3,4,5,6,7,8,9,(2010,2012,2013,2014)]
>>> _,*num,(*_,year) = data
>>> num
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> year
2014
>>> 

** 解压赋值

>>> def test(a=1,b=2,c=3):
... 	print(a,b,c)
... 	
>>> d = dict(a=4,b=5,c=6)
>>> test(**d)



你可能感兴趣的:(python)