【问题标题】:For functions that take in an indeterminate number of arguments in python, how to pass in an indeterminate number of arguments对于在python中接受不确定数量参数的函数,如何传入不确定数量的参数
【发布时间】:2011-02-23 04:49:17
【问题描述】:

例如,假设我要合并的集合数量不定:

bigSet = bigSet.union(<listOfSets>)

我可以简单地折叠每个集合,即:

bigSet = reduce(lambda x,y: x.union(y), listOfSets)

另一种选择是使用 eval 函数:

stringTuple = str(listOfSets)
stringTuple = stringTuple.strip("[")
stringTuple = stringTupl.strip("]")
bigSet = eval("bigSet.union(" + stringTuple + ")")

我问的原因是因为在 python2.6 中,将多个参数传递给联合(而不是将其折叠到联合列表中)优化联合,以便首先联合最小集合。由于 python 中的集合通常是非常大的数据集的最佳数据结构(特别是当它们需要联合或相交时),而且您有不确定数量的集合要传入似乎很常见,所以应该是一种更优化的方式来做到这一点。如果没有,哪个更快:使用 eval 还是跨集合折叠?

【问题讨论】:

    标签: python variables set functional-programming


    【解决方案1】:

    union 接受任意数量的集合作为参数:

    In [28]: x.union(set([1,2]),set([2,3]),set([3,4]))
    Out[28]: set([1, 2, 3, 4])
    

    因此,您可以将集合列表与

    bigSet = bigSet.union(*listOfSets)
    

    Note the asterisk.

    【讨论】:

      【解决方案2】:

      看起来您想将集合列表扩展为函数的参数列表,例如

      sets = [set([1,2,3]), set([3,4,5]), set([5,6,7])] 
      union(*sets)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-09
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 2015-10-08
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多