python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用

简介: python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用

在函数名前面加两个星号https://github.com/ultralytics/yolov5/blob/master/detect.py#L256

1 从示例开始认识*的作用

List = ['a', 2, 3]
Tuple = ('b', 'c', 5)
Dict = {
   'name': 'Ada', 'age': 23}

print(List)
print(Tuple)
print(Dict)

print(*List)
print(*Tuple)
print(*Dict)



import numpy as np
ndarray = np.array([2, 3, 4])
print(ndarray)
print(*ndarray)

##################################
# 输出结果如下:
'''
['a', 2, 3]
('b', 'c', 5)
{'name': 'Ada', 'age': 23}
{2, 4, 5}

a 2 3
b c 5
name age
2 4 5

[2 3 4]
2 3 4
'''

从上面可以看出:在列表、元组、字典、集合、数组前面加上*,打印的输出结果可以看出,这些数据结构中元素都被分成一个一个的独立元素

2 python函数的形参:*args 和 **kwargs 的使用

在分析列表、元组、字典、集合前加 * 的用处前,先说以下:函数中的*args 和 **kwargs这两个形参

  • *args:接收若干个位置参数转换成元组tuple形式
  • **kwargs:接收若干个关键字参数转换成字典dict形式

2.1 *args形参的使用

当传入多个位置参数,这多个位置参数会自动组成一个元组,然后我们就可以遍历这个元组中的参数啦

def fun(*args):
    print(type(args))
    print(args)
    for item in args:
        print(item)

fun(2, 'alex', [3])

# 输出结果如下
'''
<class 'tuple'>
(2, 'alex', [3])

2
alex
[3]
'''

2.2 **kwargs形参的使用

当传入多个关键字参数,这多个位置参数会自动组成一个字典,然后我们就可以遍历这个字典中的参数

def fun(**kwargs):
    print(type(kwargs))
    print(kwargs)
    for key in kwargs.keys():
        print(key, kwargs[key])


fun(name='Alvin', age=23, things=[1, 2, 'a'])

# 输出结果如下:
'''
<class 'dict'>
{'name': 'Alvin', 'age': 23, 'things': [1, 2, 'a']}

name Alvin
age 23
things [1, 2, 'a']
'''

比如下方在类Alex的构造函数中定义了多个关键字参数,然后我们在函数gen_model中就可以适用**kwargs函数,这样我们就不需要再函数gen_model中把所有对应的参数都在定义一遍,只需要在使用哪个参数,在调用的时候以关键字参数填入即可!具体实例代码如下:

class Alex(object):
    def __init__(self, block, layers, dropout_keep_prob=0, embedding=128, fp16=False):
        self.block = block
        self.layers = layers
        self.dropout_keep_prob=dropout_keep_prob
        self.embedding = embedding
        self.fp16 = fp16

        print('kwargs:', self.embedding)

    def _make_layers(self):
        raise NotImplementedError('Must be overridden by all subclasses.')



def gen_model(block, layers, **kwargs):
    model = Alex(block, layers, **kwargs)
    return model



def main():
    block = None
    layers = None
    alex_model = gen_model(block, layers, embedding=16)


if __name__ == '__main__':
    main()

**kwargs直接传入一个字典:(参考

img_norm_cfg = dict(
    mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)
train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True, with_label=False),
    dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
    dict(type='RandomFlip', flip_ratio=0.5),
    dict(type='Normalize', **img_norm_cfg),    # 直接传入一个字典
    dict(type='Pad', size_divisor=32),
    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'gt_bboxes']),
]
>>> img_norm_cfg = dict(mean=[103.530, 116.280, 123.675], std=[1.0, 1.0, 1.0], to_rgb=False)
>>> dict(type='Normalize', **img_norm_cfg)
{
   'type': 'Normalize', 'mean': [103.53, 116.28, 123.675], 'std': [1.0, 1.0, 1.0], 'to_rgb': False}
>>>

3 分析列表、元组、字典、集合和数组前加 * 有什么用处

参考

def print_item(*args):
    print(type(args))
    print(args)
    for item in args:
        print(item)


List = ['apple', 23, 'orange', 9]
print_item(List)
print_item(*List)


# 打印输出结果
'''
<class 'tuple'>
(['apple', 23, 'orange', 9],)  # 这个元组里面只有一个元素
['apple', 23, 'orange', 9]

<class 'tuple'>
('apple', 23, 'orange', 9)  # 加星号之后,直接把列表中的元素都取出来放到一个元组中,然后可以直接遍历
apple
23
orange
9
'''
目录
相关文章
|
16天前
|
存储 数据处理 索引
如何删除 Python 数组中的值?
【8月更文挑战第29天】
22 8
|
16天前
|
索引 Python
向 Python 数组添加值
【8月更文挑战第29天】
25 8
|
16天前
|
存储 缓存 C语言
|
16天前
|
存储 测试技术 Python
Python 数组和列表有什么区别?
【8月更文挑战第29天】
22 4
|
16天前
|
索引 Python 容器
为什么Python中会有集合set类型?
为什么Python中会有集合set类型?
|
15天前
|
机器学习/深度学习 存储 算法
NumPy 与 SciPy:Python 科学计算库的比较
【8月更文挑战第30天】
41 1
|
15天前
|
存储 C语言 Python
|
16天前
|
存储 数据库 Python
Python 中的字典是什么?
【8月更文挑战第29天】
14 0
|
3天前
|
存储 人工智能 数据挖掘
Python编程入门:从基础到实战
【9月更文挑战第10天】本文将引导你进入Python编程的世界,从基本语法到实际项目应用,逐步深入。我们将通过简单的例子和代码片段,帮助你理解并掌握Python编程的精髓。无论你是编程新手还是有一定经验的开发者,都能在这篇文章中找到有价值的信息。让我们一起开始Python编程之旅吧!