如何编写接受任意数量参数的 Python 函数
问题
你要编写一个能接受任意数量输入参数的函数。
解决方案
Python 中的 * 参数可接受任意数量的参数。我们来看一个求取任意两个或更多个数字的平均值的例子就能理解这个概念。在下例中,rest_arg 是一个包含所有附加参数(本例中为数字)的元组。此函数在执行平均值计算时,将这些参数视为序列。
# Sample function to find the average of the given numbers
def define_average(first_arg, *rest_arg):
average = (first_arg + sum(rest_arg)) / (1 + len(rest_arg))
print(f"Output \n *** The average for the given numbers {average}")
# Call the function with two numbers
define_average(1, 2)输出
*** The average for the given numbers 1.5
# Call the function with more numbers define_average(1, 2, 3, 4)
输出
*** The average for the given numbers 2.5
要接受任意数量的关键字参数,请使用以 ** 开头的参数。
def player_stats(player_name, player_country, **player_titles):
print(f"Output \n*** Type of player_titles - {type(player_titles)}")
titles = ' AND '.join('{} : {}'.format(key, value) for key, value in player_titles.items())
print(f"*** Type of titles post conversion - {type(titles)}")
stats = 'The player - {name} from {country} has {titles}'.format(name = player_name,
country=player_country,
titles=titles)
return stats
player_stats('Roger Federer','Switzerland', Grandslams = 20, ATP = 103)输出
*** Type of player_titles - <class 'dict'> *** Type of titles post conversion - <class 'str'>
'The player - Roger Federer from Switzerland has Grandslams : 20 AND ATP : 103'
在上例中,player_titles 为一个包含传递过来的关键字参数的字典。
如果你想编写一个可以同时接收任意数量的位置参数和关键字专用参数的函数,请同时使用 * 和 **。
def func_anyargs(*args, **kwargs): print(args) # A tuple print(kwargs) # A dict
通过使用此函数,所有位置参数都将放入元组 args 中的所有关键字参数都将放入字典 kwargs 中。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP