如何运用PYTHON里*args和*kwargs

 时间:2026-02-17 04:21:32

1、打开Python,新建一个空白的PY文档。

如何运用PYTHON里*args和*kwargs

2、def new_students(*args):

    for all_students in args:

        print(all_students)

the_list = ["Peter", "Cherry", "Ben", "Ken", "Lee"]

new_students(*the_list)

首先我们用for loops来把list里面的所有值给打印出来。

如何运用PYTHON里*args和*kwargs

3、def new_students(*args):

    for all_students in args:

        print(all_students)

the_list = ["Peter", "Cherry", "Ben", "Ken", "Lee"]

new_students(the_list)

如果不加*,那么只会整个列表呈现出来,而不是只把值给返回来。

如何运用PYTHON里*args和*kwargs

4、new_students("Peter", "Cherry", "Ben", "Ken", "Lee")

虽然可以用普通的方式把列表的值给打印出来,但是如果里面的值非常多,那么工作量很大,而且容易出错,所以*args可以很好地表现。

如何运用PYTHON里*args和*kwargs

5、def new_student(classroom, year, *args):

    print(classroom)

    print(year)

    for all in args:

        print(all)

the_list = ["Peter", "Cherry", "Ben", "Ken", "Lee"]

new_student("001", "2018", *the_list)

增加两个变量在前面也不影响使用。

如何运用PYTHON里*args和*kwargs

6、def new_students(*args):

    for all_students in args:

        print(all_students)

the_list = ("Peter", "Cherry", "Ben", "Ken", "Lee")

new_students(*the_list)

除了list,tuples也是可以运用得上。

如何运用PYTHON里*args和*kwargs

7、def details(**kwargs):

    for key, value in kwargs.items():

        print(key)

        print(value)

contact = {"Peter":"18", "Alice":"16", "Ben":"17"}

details(**contact)

**kwargs对应的要用dictionary。

如何运用PYTHON里*args和*kwargs

  • vscode中的如何自动将代码格式化成eslint风格
  • oracle如何给用户分配权限与角色并回收
  • Carbon 代码分享工具如何使用?
  • linux下如何用anaconda创建python虚拟环境
  • c#中接口的使用
  • 热门搜索
    甘肃 旅游 长白山旅游报价 大连旅游局 出游客旅游网 旅游官方网站 旅游攻略蚂蜂窝 云南旅游包车 大溪地旅游 意大利旅游签证 北京清明节旅游