Loading

Python元组、列表前加 * 号

先看演示代码

list = [1,2,3,4]
print(*list)

def add(*args):
    print(type(args))
    print(args)
    for i in args:
        print(i)
add(list)
print('------------------------------')
add(*list)

输出如下

1 2 3 4
<class 'tuple'>
([1, 2, 3, 4],)
[1, 2, 3, 4]
------------------------------
<class 'tuple'>
(1, 2, 3, 4)
1
2
3
4
  1. 在列表前加*会将列表拆解为一个一个的元素
  2. 在函数中使用 * 时,可以按如下理解

*args = *list ====> 将list直接传递给args,但类型转换为元组

*args = list ====> args加上*(拆解)等于list,反过来想,args就等于list再套上一层,即(list,)

posted @ 2021-05-24 22:40  紫曜花  阅读(546)  评论(0编辑  收藏  举报