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.youkuaiyun.com/weixin_40877427/article/details/82931899
本文主要介绍Python中在列表、元组、字典变量前加星号的用法。一个星号可将列表解开成独立参数传入函数,两个星号可将字典解开成独立元素作为形参。序列加星号相当于解压,与zip功能相反,还给出了相关参考链接。
333

被折叠的 条评论
为什么被折叠?



