【问题标题】:How do I pass tuples elements to a function as arguments?如何将元组元素作为参数传递给函数?
【发布时间】:2012-05-24 09:50:30
【问题描述】:

我有一个由元组组成的列表,我想将每个元组的元素作为参数传递给函数:

mylist = [(a, b), (c, d), (e, f)]

myfunc(a, b)
myfunc(c, d)
myfunc(e, f)

我该怎么做?

【问题讨论】:

    标签: python list arguments tuples


    【解决方案1】:

    明确@DSM 的评论:

    >>> from itertools import starmap
    >>> list(starmap(print, ((1,2), (3,4), (5,6)))) 
    # 'list' is used here to force the generator to run out.
    # You could instead just iterate like `for _ in starmap(...): pass`, etc.
    1 2
    3 4
    5 6
    [None, None, None] # the actual created list;
    # `print` returns `None` after printing.
    

    【讨论】:

    • 我认为这是一个坏主意 - 您正在构建一个您实际上并不想要的列表。丑陋且不清楚。
    • starmap 迭代器可以使用,但需要使用。在我们想要“将每个元组的元素作为参数传递给函数”的情况下,通常也想要对函数调用的结果做一些事情。如果不是,for _ in starmap(...): pass 是合适的。
    • 它完成了这项工作,但为什么要这样做而不是正常的 for 循环呢?阅读该代码的任何人都不太清楚。
    【解决方案2】:

    这在 Python 中实际上非常简单,只需遍历列表并使用 splat 运算符 (*) 将元组解包为函数的参数:

    mylist = [(a, b), (c, d), (e, f)]
    for args in mylist:
        myfunc(*args)
    

    例如:

    >>> numbers = [(1, 2), (3, 4), (5, 6)]
    >>> for args in numbers:
    ...     print(*args)
    ... 
    1 2
    3 4
    5 6
    

    【讨论】:

    • 另见itertools.starmap
    • func(*args) 语法并非特定于 3.x,但 print 是一个函数,因此示例将在 2.x 上的 print(*args) 上给出语法错误。
    • 您可能认为您在 2.x 上使用 print 作为函数,因为您使用了括号,但如果只有一个值,括号实际上并没有做任何事情。例如print(1)print 1 相同。您也可以对其他语句执行相同的操作,例如 return(1) 等同于 return 1
    • 在 Python 2.x 上你可以创建一个简单的函数来打印每个参数,例如你可以使用def _print(*args): print ' '.join(map(str, args))
    • Python 2.x 中的另一个选项是从未来导入打印功能 - from __future__ import print_function
    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多