作者:mingrammer
翻译:老齐
与本文相关的图书推荐:《Python大学实用教程》
与其他编程语言相比,Python语言的操作类型更多样化。
特别是星号(*),在Python中是一个用途广泛的操作符,而不仅仅用于两个数字相乘的运算之中。在本文中,我们将讨论星号的多种用途。
这里总结了4种星号的应用场景:
- 作为乘法和乘方的运算符
- 表示序列中元素的重复
- 用于收集参数(可以称之为“打包”)
- 用于容器类对象的解包
下面逐一进行说明。
乘法或乘方的运算符
对此你一定不陌生,像乘法一样,Python中也内置了乘方运算符。
>>> 2 * 3
6
>>> 2 ** 3
8
>>> 1.414 * 1.414
1.9993959999999997
>>> 1.414 ** 1.414
1.6320575353248798
复制代码
重复类列表的容器元素
Python也支持类列表的容器类对象(即序列)与整数相乘,即为按照整数实现重复其中的元素数量。
# Initialize the zero-valued list with 100 length
zeros_list = [0] * 100
# Declare the zero-valued tuple with 100 length
zeros_tuple = (0,) * 100
# Extending the "vector_list" by 3 times
vector_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]
复制代码
参数收集
很多函数中,都会有不确定个数的参数。例如,如果我们不知道要提供多少个参数,或者因为什么原因必须传任意个参数等。
在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 arguments
save_ranking('ming', 'alice')
# Pass the 2 positional arguments and 1 keyword argument
save_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):
...
复制代码
但是,在
save_ranking('alice', 'ming', 'mike', fourth='jim')
调用中,提供了3个位置实参和一个关键词参数。是的,对于关键词参数,你也可以按照位置参数的方式传值,所对应的关键词能够接受依据位置所传的数据。按照此处的调用方法,
'mike'
就自动传给了
third
。