英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论