python中拆包解包用法详解

python可以对元组和字典进行拆包或解包操作。

1、拆包:元组

示例代码1:

def return_num():
    return 100, 200


num1, num2 = return_num()
print(num1)  # 100
print(num2)  # 200

运行结果:

python中拆包解包用法详解_第1张图片

示例代码2:

def return_num1():
    return 100, 200


def return_num2():
    return 100, 200, 300


def return_num3():
    return 100, 200, 300, 400, 500


def func(num1, num2):
    print(num1, num2)


def func2(num1, num2, *args):
    print(num1, num2, args)


if __name__ == '__main__':
    func(*return_num1())
    # func(*return_num2())  # 报错:TypeError: func() takes 2 positional arguments but 3 were given
    func2(*return_num1())
    func2(*return_num2())
    func2(*return_num3())

运行结果:

python中拆包解包用法详解_第2张图片

2、拆包:字典

示例代码1:

dict1 = {'name': 'TOM', 'age': 18}
a, b = dict1

# 对字典进⾏拆包,取出来的是字典的key
print(a)  # name
print(b)  # age
print(dict1[a])  # TOM
print(dict1[b])  # 18

运行结果:

python中拆包解包用法详解_第3张图片

示例代码2:

dic = {'aa': 'AA', 'bb': 'BB'}
dic2 = {'aa': 'AA', 'bb': 'BB', 'cc': 'CC'}
dic3 = {'aa': 'AA'}


def func(aa, bb):
    print(aa, bb)


if __name__ == '__main__':
    func(**dic)
    # func(**dic2)  # 此时报错:TypeError: func() got an unexpected keyword argument 'cc'
    # func(**dic3)  # 此时报错:TypeError: func() missing 1 required positional argument: 'bb'

运行结果:

python中拆包解包用法详解_第4张图片

示例代码3:

dic = {'aa': 'AA', 'bb': 'BB'}
dic2 = {'aa': 'AA', 'bb': 'BB', 'cc': 'CC', 'dd': 'DD'}
dic3 = {'aa': 'AA'}


def func(aa, bb, **kwargs):
    print(aa, bb, kwargs)
    print(aa, bb, kwargs.get('cc'))


if __name__ == '__main__':
    func(**dic)
    func(**dic2)

运行结果:

python中拆包解包用法详解_第5张图片

你可能感兴趣的:(python基础,python,拆包)