Python中的双星运算符是什么意思?
双星或 (**) 是Python语言中的算术运算符之一(如 +、-、*、**、/、//、%)。它也被称为电力运营商。
算术运算符的优先级是什么?
算术运算运算符遵循与数学相同的优先规则,它们是:先执行指数,然后执行乘法和除法,然后是加法和减法。
递减模式下的算术运算运算符优先级顺序:
() >> ** >> * >> / >> // >> % >> + >> -
双星运算符的用途:
作为幂运算符
对于数值数据类型,双星号 (**) 被定义为幂运算符:
例子:
Python3
# Python code to Demonstrate the Exponential Operactor
a = 2
b = 5
# using double asterisk operator
c = a**b
print(c)
# using double asterisk operator
z = 2 * (4 ** 2) + 3 * (4 ** 2 - 10)
print(z)
Python3
# Python Program to create a function to get a dictionary of names.
# Here, we will start with a dictionary of three names
def function(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
function(name_1="Shrey", name_2="Rohan", name_3="Ayush")
Python3
# Python Program to create a function to get a dictionary of as many names
# you want to include in your Dictionary
def function(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
function(
name_1="Ayush",
name_2="Aman",
name_3="Harman",
name_4="Babber",
name_5="Striver",
)
输出:
32
50
作为函数和方法中的参数
在函数定义中,双星号也称为**kwargs 。他们过去常常将关键字、可变长度参数字典传递给函数。两个星号 (**) 是这里的重要元素,因为kwargs一词通常被使用,尽管语言并未强制使用。
首先,让我们简单地打印出我们传递给函数的**kwargs参数。我们将创建一个简短的函数来执行此操作:
例子:
蟒蛇3
# Python Program to create a function to get a dictionary of names.
# Here, we will start with a dictionary of three names
def function(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
function(name_1="Shrey", name_2="Rohan", name_3="Ayush")
输出:
The value of name_1 is Shrey
The value of name_2 is Rohan
The value of name_3 is Ayush
现在这里是另一个例子,我们将向函数传递额外的参数,以表明**kwargs将接受任意数量的参数:
蟒蛇3
# Python Program to create a function to get a dictionary of as many names
# you want to include in your Dictionary
def function(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
function(
name_1="Ayush",
name_2="Aman",
name_3="Harman",
name_4="Babber",
name_5="Striver",
)
输出:
The value of name_1 is Ayush
The value of name_2 is Aman
The value of name_3 is Harman
The value of name_4 is Babber
The value of name_5 is Striver
结论:
使用**kwargs为我们提供了在程序中使用关键字参数的灵活性。当我们使用**kwargs作为参数时,我们不需要知道我们最终想要传递给函数的参数数量。创建接受**kwargs的函数最适合在您期望参数列表中的输入数量保持相对较小的情况下使用。