一文弄懂Python中的星号用法

公司资讯 admin 发布时间:2024-08-08 浏览:1 次

01

引言

与其他语言相比,Python 拥有丰富的操作类型。尤其是星号(*),它是 Python 中最常用的运算符之一,除了两数相乘之外,它还允许我们进行各种操作。在本篇文章中,我们将探讨如何使用星号(*)进行各种运算,从而加深大家对该运算符的理解。

闲话少说,我们直接开始吧!

02

 用于乘法和幂运算

这是星号最常用的情况,大家应该早就知道这种用力。Python 支持内置的幂运算和乘法运算。

>>> 2 * 3 6 >>> 2 ** 3 8 >>> 1.414 * 1.414 1.9993959999999997>>> 1.414 ** 1.4141.6320575353248798

03

 用于重复扩展列表

Python 还支持使用数字乘以 list 类型容器(包括元组),来实现按给定次数扩展容器数据。

# Initialize the zero-valued list with 100 lengthzeros_list = [0] * 100 # Declare the zero-valued tuple with 100 lengthzeros_tuple = (0,) * 100 # Extending the "vector_list" by 3 timesvector_list = [[1, 2, 3]] for i, vector in enumerate(vector_list * 3): print("{0} scalar product of vector: {1}".format((i + 1), [(i + 1) * e for e in vector]))# 1 scalar product of vector: [1, 2, 3]# 2 scalar product of vector: [2, 4, 6]# 3 scalar product of vector: [3, 6, 9]

04

 用于可变参数

我们经常需要在某些函数中使用可变参数(或参数)。例如,如果我们不知道传递参数的个数,或者由于某些原因我们需要用任意传递参数来处理某些事情,我们就需要它。

Python 中有两种参数,一种是位置参数,另一种是关键字参数,前者是根据位置指定的,后者是带有关键字的参数,关键字是参数的名称。

在了解可变参数/关键字参数之前,我们先简单谈谈位置参数和关键字参数。

# A function that shows the results of running competitions consisting of 2 to 4 runners.def save_ranking(first, second, third=None, fourth=None): rank = {} rank[1], rank[2] = first, second rank[3] = third if third is not None else Nobody rank[4] = fourth if fourth is not None else Nobody print(rank) # Pass the 2 positional argumentssave_ranking(ming, alice)# Pass the 2 positional arguments and 1 keyword argumentsave_ranking(alice, ming, third=mike)# Pass the 2 positional arguments and 2 keyword arguments (But, one of them was passed as like positional argument)save_ranking(alice, ming, mike, fourth=jim)

上述函数共有2个位置参数:first、second和 2 个关键字参数:third、fourth。对于位置参数,不能省略,必须根据声明的参数个数将所有位置参数传递到正确的位置。但是,对于关键字参数,可以在声明函数时设置默认值,如果省略参数,则相应的默认值将作为参数值输入。也就是说,关键字参数是可以省略的。

正是因为关键字参数可以省略,所以不能在位置参数之前声明关键字参数。因此,下面的代码会引发异常:

def save_ranking(first, second=None, third, fourth=None): ...

到目前为止,我们已经讨论了基础函数参数知识。顺便提一下,这里可能会遇到一个问题。函数无法处理任意数量的参数,因为函数的参数数量是固定的。因此,我们需要可变参数。位置参数和关键字参数都可以用作变量参数。让我们看看下面的示例。

星号仅用作位置参数示例:

def save_ranking(*args): print(args) save_ranking(ming, alice, tom, wilson, roy)# (ming, alice, tom, wilson, roy)

星号仅用作关键字参数示例:

def save_ranking(**kwargs): print(kwargs)save_ranking(first=ming, second=alice, fourth=wilson, third=tom, fifth=roy)# {first: ming, second: alice, fourth: wilson, third: tom, fifth: roy}

星号同时用作位置参数和关键字参数示例:

def save_ranking(*args, **kwargs): print(args) print(kwargs)save_ranking(ming, alice, tom, fourth=wilson, fifth=roy)# (ming, alice, tom)# {fourth: wilson, fifth: roy}

其中,*args 表示接受任意数量的位置参数,**kwargs 表示接受任意数量的关键字参数。

05

用作解包

星号也可用于解压缩容器。其原理与上文的 "用于使用变量参数 "类似。最简单的例子是,我们有 list、tuple 或 dict 形式的数据,而函数的参数是可变的:

from functools import reduceprimes = [2, 3, 5, 7, 11, 13]def product(*numbers): p = reduce(lambda x, y: x * y, numbers) return p product(*primes)# 30030product(primes)# [2, 3, 5, 7, 11, 13]

由于 product() 函数使用了可变参数,因此我们需要解包列表数据并将其传递给该函数。在这种情况下,如果我们将 列表primes 作为 *primes 传递,那么 primes 列表中的每个元素都将被解包,然后存储在名为 numbers 的列表中。

还有一种解包方式,它不是针对函数的,而是将 list 或 tuple 数据动态解包到其他变量中。

numbers = [1, 2, 3, 4, 5, 6]# The left side of unpacking should be list or tuple.*a, = numbers# a = [1, 2, 3, 4, 5, 6]*a, b = numbers# a = [1, 2, 3, 4, 5]# b = 6a, *b, = numbers# a = 1 # b = [2, 3, 4, 5, 6]a, *b, c = numbers# a = 1# b = [2, 3, 4, 5]# c = 6

在这里,*a 和 *b 将再次打包剩余的值,除了单个未打包的值,这些值在解包 list 或 tuple 后将分配给其他普通变量。这与变量参数的打包概念相同。

06

总结

到目前为止,我们已经介绍了 Python 的星号 (*)。能用一个运算符完成各种操作是一件非常有趣的事情,而且上面的大部分操作都是编写 Python 代码的基础。尤其是 "对于使用可变参数 "是非常重要的,但 Python 初学者经常对这个概念感到困惑,所以如果你是 Python 初学者,我希望你能更好地了解它。

您学废了嘛?

点击上方小卡片关注我

扫码进群,交个朋友!

在线咨询

点击这里给我发消息售前咨询专员

点击这里给我发消息售后服务专员

在线咨询

免费通话

24h咨询:400-888-8888


如您有问题,可以咨询我们的24H咨询电话!

免费通话

微信扫一扫

微信联系
返回顶部