[英]For functions that take in an indeterminate number of arguments in python, how to pass in an indeterminate number of arguments
For example, say I have an indterminate number of sets I want to union: 例如,假设我要合并的集合数不确定:
bigSet = bigSet.union(<listOfSets>)
I could simply fold across each set, ie : 我可以简单地折叠每组,即:
bigSet = reduce(lambda x,y: x.union(y), listOfSets)
Another alternative is to use the eval function: 另一种选择是使用eval函数:
stringTuple = str(listOfSets)
stringTuple = stringTuple.strip("[")
stringTuple = stringTupl.strip("]")
bigSet = eval("bigSet.union(" + stringTuple + ")")
The reason I ask is because in python2.6, passing multiple arguments into union (rather than folding it across a list of unions) optimizes the union-ing so that the smallest sets are union-ed first. 我问的原因是因为在python2.6中,将多个参数传递给并集(而不是将其折叠到并集列表中)可优化并集,以便最小的集合首先被并集。 As sets in python are often the best data structure for very large datasets (especially when they need to be union-ed or intersected), and it seems pretty common that you'd have an indeterminate number of sets to pass in, so there should be a more optimal way to do this.
由于python中的集合通常是非常大的数据集的最佳数据结构(尤其是当它们需要合并或相交时),并且传入的集合数不确定是很常见的,因此应该成为执行此操作的最佳方法。 If there isn't, which is faster: using eval or folding across the sets?
如果没有,那是更快的:使用eval还是在集合之间折叠?
union
accepts an arbitrary number of sets as arguments: union
接受任意数量的集合作为参数:
In [28]: x.union(set([1,2]),set([2,3]),set([3,4]))
Out[28]: set([1, 2, 3, 4])
Therefore, you can union a list of sets with 因此,您可以使用
bigSet = bigSet.union(*listOfSets)
Looks like you want to expand a list of sets into argument list of a function eg 看起来您想将集合列表扩展为函数的参数列表,例如
sets = [set([1,2,3]), set([3,4,5]), set([5,6,7])]
union(*sets)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.