有没有办法在 Python 函数中使用 1 个以上的可变长度参数 (*args)?

发布于 2024-12-08 16:37:02 字数 217 浏览 1 评论 0原文

我想创建一个使用两个可变长度参数的函数。例如:

def my_func(*args1, *args2):
    for i in args1:
        do stuff
    for j in args2:
        do stuff

Python中有没有一种方法可以使用多个*args?预先感谢您的帮助。

I would like to create a function that uses two variable length arguments. For example:

def my_func(*args1, *args2):
    for i in args1:
        do stuff
    for j in args2:
        do stuff

Is there a way in Python to use more than one *args? Thanks in advance for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夏夜暖风 2024-12-15 16:37:02

不,因为无法确定是否

my_func(a, b)

意味着

args = [], args2 = [a,b] # or ..
args = [a], args2 = [b]  # or ..
args = [a,b], args2 = []

相反,只需让函数采用两个列表作为参数即可。

No, as there is no way to decide whether

my_func(a, b)

means

args = [], args2 = [a,b] # or ..
args = [a], args2 = [b]  # or ..
args = [a,b], args2 = []

Instead, simply let the function take two lists as arguments.

冷心人i 2024-12-15 16:37:02

你应该使用列表。这样,哪个项目属于哪个参数就很明显了:

def my_func(args1, args2):
    for a in args1:
        print a
    for b in args2:
        print b

my_func([1, 2, 3], [4, 5, 6])

You should use lists. That way, it's obvious which item goes in which argument:

def my_func(args1, args2):
    for a in args1:
        print a
    for b in args2:
        print b

my_func([1, 2, 3], [4, 5, 6])
很酷不放纵 2024-12-15 16:37:02

您可以为每个参数使用一个数组(或者任何 Python 中数组的名称)。否则,Python 无法知道在哪里分割每组可变长度参数。

You could use an array (or whatever Python's name for an array is) for each argument. Otherwise, there's no way for Python to know where to split each set of variable length arguments.

猥︴琐丶欲为 2024-12-15 16:37:02

您想如何调用该函数?为什么不使用两个 arrys 或 dicts ?

How would you like to call the function? why not use two arrys or dicts?

半﹌身腐败 2024-12-15 16:37:02

不,这甚至没有意义。什么决定了第一个列表中的内容和第二个列表中的内容?不过,您也可以传递关键字参数(如果您还不知道):

def func(*args **kwargs):
    pass

您到底想要完成什么?

No that doesn't even make sense. What would determine what goes in the first list and what goes in the second? You can pass keyword arguments as well, though (in case you didn't know already):

def func(*args **kwargs):
    pass

What exactly is it that you are trying to accomplish?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文