如何编写接受任意数量参数的Python函数

如何编写接受任意数量参数的Python函数

更多Python相关文章,请阅读: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中。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程