有办法让 Python 函数接受重复的参数集吗?

huangapple go评论64阅读模式
英文:

Is there a way to give Python functions repeating sets of arguments?

问题

对于重复参数,我了解 args 和 **kwargs,但有没有办法创建一个具有可变数量集*参数的函数?

例如:

def move(dir1, num1, dir2, num2, dir3, num3, ... dirN, numN):

这样的函数可以让你告诉某物按任意数量的方向移动任意数量的空间。

英文:

I know about *args and **kwargs for repeating arguments, but is there a way to create a function with a variable number of sets of arguments?

E.g.

def move(dir1, num1, dir2, num2, dir3, num3, ... dirN, numN):

for a function that would allow you to tell something to move something any number of directions by any number of spaces.

答案1

得分: 4

你可以接受一个指定移动顺序的元组列表。

例如:

def move(moves):
    for direction, num in moves:
        print(direction, num)
move([('N', 1), ('E', 2)])
英文:

You could accept a list of tuples specifying a sequence of moves instead.

For example:

def move(moves):
    for direction, num in moves:
        print(direction, num)
move([('N', 1), ('E', 2)])

答案2

得分: 1

你可以在函数定义中使用 *params,其中每个参数都是一个包含方向和数字的元组:

def move(*dir_nums):
    for direction, number in dir_nums:
        print(f"{direction=}, {number=}")
        
move(('N', 1), ('E', 2), ('W', 3))
# direction='N', number=1
# direction='E', number=2
# direction='W', number=3
英文:

You could use *params in the function definition, which each parameter is a tuple of a direction and a number:

In [1]: def move(*dir_nums):
   ...:     for direction, number in dir_nums:
   ...:         print(f"{direction=}, {number=}")
   ...: 
   ...: 
   ...: move(('N',1),('E',2),('W',3))
# direction='N', number=1
# direction='E', number=2
# direction='W', number=3

huangapple
  • 本文由 发表于 2023年2月18日 10:52:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定