三分钟带你看懂python中*和**的使用

一,*的使用

1.作为乘法运算符来使用
print(3*5)
#输出15
2,(1)作为收集任意数量的参数来使用

a,b,*c=[1,2,3,4]
#a=1 b=2 c=[3,4]
*c会收集剩余的参数并且将其组合为一个列表输出

(2)定义函数中也可以收集任意数量的实参

def example(example_1,*example_2):
print(f”{example_1}and the{example_2})
example(a,b,c,d)
example(1,2,3)
#输出“a and the b,c,d”
#输出”1 and the 2,3″
该函数先依据位置实参将a传入example_1,再将剩余数量的实参传入example_2

(3)定义函数时收集参数组成为元组导出

def example(*example_3):
print(example_3)
example(1,2,3)
example(a)
#输出(1,2,3)
#输出(a,)
3,导入模块中的所有函数

from collections import *
此时可以使用collections模块中的所有函数,但是为了更加便于理解和阅读代码,不建议使用这种方法。

注意:在定义函数使用*example_2时,不要给后面再添加形参,因为python会分不清楚*example_2是否该接收剩下的所有值而报错。

二,**的用法

**用于收集关键字参数从而组成字典输出

def example(**example_4):
print(example_4)
example(“name”:”mike”,”age”:18)
#输出”{“name”:”mike”,”age”:18}
三,*与**有关拆包的使用

def text_one(a,b,c):
print(a,b,c)
tu=(1,2,3)
text_one(*tu)
#输出a=1 b=2 c=3
使用*将元组tu拆分再分配给a,b,c

同理

def text_two(*nums, **dict):
print(nums)
print(dict)
nums = (‘a’, “b”, “c”)
dict = {“name”: “mike”, “age”: 18}
text_two(*nums, **dict)
#输出(‘a’, ‘b’, ‘c’)
#{‘name’: ‘mike’, ‘age’: 18}
如果不加星号最终的输出将会变为((“a”,”b”,”c”){“name:”mike”,”age”:18})
————————————————
版权声明:本文为CSDN博主「下水道程序员」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Cobrander2_0/article/details/127343398

(文章今日已有 1 人访问,总访问量 28 ::>_<::)
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇