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, i.e. :
bigSet = reduce(lambda x,y: x.union(y), listOfSets)
Another alternative is to use the eval function:
stringTuple = str(listOfSets)
stringTuple = stringTuple.strip("[")
stringTuple = stringTupl.strip("]")
bigSet = eval("bigSet.union(" + stringTuple + ")")
The reason I ask is because in python2.6, pas开发者_开发知识库sing 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. 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. If there isn't, which is faster: using eval or folding across the sets?
union
accepts an arbitrary number of sets as arguments:
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)
Note the asterisk.
Looks like you want to expand a list of sets into argument list of a function e.g.
sets = [set([1,2,3]), set([3,4,5]), set([5,6,7])]
union(*sets)
精彩评论