Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python集用法、返回联合、类型灵活性权衡_Python_Types_Set - Fatal编程技术网

Python集用法、返回联合、类型灵活性权衡

Python集用法、返回联合、类型灵活性权衡,python,types,set,Python,Types,Set,我一直在用电视机 >>> 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 se

我一直在用电视机

>>> 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
对于这样做的函数,我的最佳选择似乎是:

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
,但是第二个将提供更大的灵活性。我的问题是:

确保始终将此函数传递给一个集合,我会得到什么好处吗?

传递任何iterable的灵活性值得吗?

您可以用于返回联合的就地更新

从文件中引用

更新集合,从所有其他集合中添加元素

范例

>>> s1 = set('a')
>>> s1.update('ba')
>>> s1
set(['a', 'b'])
是否希望能够传递任意iterable?除了一套之外,你还要通过别的考试吗?用你的方式回答你的问题有点难。确保它是一个集合的优点是,如果它不是,你会得到一个响亮的警告。灵活性是否“值得”,取决于你对其他东西做了什么。如果要联合的对象是需要单独作为集合进行操作的集合,那么最好将它们作为集合进行处理。如果它们总是列表和/或元组,因为您在其他上下文中将它们用作列表/元组,那么接受任何iterable都是有意义的

>>> s1 = set('a')
>>> s1.update('ba')
>>> s1
set(['a', 'b'])