簡體   English   中英

對於在python中使用不確定數量的參數的函數,如何傳遞不確定數量的參數

[英]For functions that take in an indeterminate number of arguments in python, how to pass in an indeterminate number of arguments

例如,假設我要合並的集合數不確定:

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還是在集合之間折疊?

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)

注意星號

看起來您想將集合列表擴展為函數的參數列表,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM