Python *和**的解包用法
Python中的*
和**
具有多种用途,此处演示解包功能。
示例:
def f_test(*args, **kwargs):
print('args:', args)
print('kwargs:', kwargs)
#
if __name__ == '__main__':
data = [['小太阳', 10, 20], ['鼠标', 21, 31], ['小刀', 51, 81], ['手机壳', 16, 100]]
dict_data = {'a': '11', 'b': '22', 'c': '33', 'd': '44'}
list_a = ['小太阳', '小太阳123', '小太阳456']
tup_b = ('a1', 'a2', 'a3')
# 解压缩
print('*data:', *data)
print('*dict_data:', *dict_data)
print('*list_a:', *list_a)
print('*tup_b:', *tup_b)
first_element, surplus_element = data[0], data[1:]
first_element2, *surplus_element2 = data
print('')
print('first_element:', first_element)
print('surplus_element:', surplus_element)
print('')
print('first_element2:', first_element2)
print('surplus_element2:', surplus_element2)
first_element3, *surplus_element3, last_element3 = data
print('')
print('first_element3:', first_element3)
print('surplus_element3:', surplus_element3)
print('last_element3:', last_element3)
# 定义参数
print('\nf_test1:')
f_test(1, 2, 3, a=11, b=12, c=13)
print('\nf_test2:')
f_test(**dict_data)
打印结果:
*data: ['小太阳', 10, 20] ['鼠标', 21, 31] ['小刀', 51, 81] ['手机壳', 16, 100]
*dict_data: a b c d
*list_a: 小太阳 小太阳123 小太阳456
*tup_b: a1 a2 a3
first_element: ['小太阳', 10, 20]
surplus_element: [['鼠标', 21, 31], ['小刀', 51, 81], ['手机壳', 16, 100]]
first_element2: ['小太阳', 10, 20]
surplus_element2: [['鼠标', 21, 31], ['小刀', 51, 81], ['手机壳', 16, 100]]
first_element3: ['小太阳', 10, 20]
surplus_element3: [['鼠标', 21, 31], ['小刀', 51, 81]]
last_element3: ['手机壳', 16, 100]
f_test1:
args: (1, 2, 3)
kwargs: {'a': 11, 'b': 12, 'c': 13}
f_test2:
args: ()
kwargs: {'a': '11', 'b': '22', 'c': '33', 'd': '44'}