我一直在使用集相當多。Python設置使用,返回聯合,折衷類型的折衷
>>> s1
set(['a', 'b'])
使用方法允許進行類型轉換,而重載操作符則不允許。
>>> s1.issubset('abc')
True
>>> s1 <= 'abc'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only compare to a set
>>> s1 <= set('abc')
True
我希望能夠以一組與工會團結起來,在功能的另一組:
>>> s1 | set('bc') # returns the union without modifying either
set(['a', 'c', 'b'])
>>> s1.union('bc') # allows for type conversion.
set(['a', 'c', 'b'])
看來我的最佳選擇了,做這樣的功能是:
def add_elements_strict(collector_set):
do_stuff()
return collector_set | more_elements()
或者像這樣。
def add_elements_from_any_iterable(collector_set):
do_stuff()
return collector_set.union(more_elements())
哪個會更好?很明顯,如果給定一個集合,第一個將給出TypeError
,但第二個會給予更大的靈活性。我的問題:
從確保我總是通過這個函數一套,我會獲得什麼嗎?
靈活性能夠通過任何可迭代值得嗎?