python 里面列表前面加星号的意思

python 里面列表前面加星号, add([1,5])这是什么用法?
例如
from operator import add
add(
[1,5])
6

作用是将列表解开成两个独立的参数,传入函数,还有类似的有两个星号,是将字典解开成独立的元素作为形参。

# -*- coding:utf-8 -*-
 
def add(a, b):
    return a+b
 
data = [4,3]
print add(*data)
#equals to print add(4, 3)
data = {'a' : 4, 'b' : 3}
print add(**data)
#equals to print add(4, 3)

python 在列表,元组,字典变量前加*号
废话不说,直接上代码(可能很多人以前不知道有这种方法):

a=[1,2,3]
b=(1,2,3)
c={1:“a”,2:“b”,3:“c”}
print(a,"",*a)
print(b,"
",*b)
print(c,"====",*c)

运行结果为:
[1, 2, 3] ==== 1 2 3
(1, 2, 3) ==== 1 2 3
{1: ‘a’, 2: ‘b’, 3: ‘c’} ==== 1 2 3

序列+*相当于解压,与zip的功能相反

参考:
https://zhidao.baidu.com/question/2140001532025683868.html
https://www.cnblogs.com/linwenbin/p/10362811.html
https://blog.csdn.net/weixin_40877427/article/details/82931899

猜你喜欢

转载自blog.csdn.net/hellenlee22/article/details/89740923
今日推荐