Creating an empty set

后端 未结 4 2054
刺人心
刺人心 2021-01-03 23:15

I have some code which tots up a set of selected values. I would like to define an empty set and add to it, but {} keeps turning into a dictionary. I have foun

相关标签:
4条回答
  • 2021-01-03 23:35

    A set literal is just a tuple of values in curly braces:

    x = {2, 3, 5, 7}
    

    So, you can create an empty set with empty tuple of values in curly braces:

    x = {*()}
    

    Still, just because you can, doesn't mean you should.

    Unless it's an obfuscated programming, or a codegolf where every character matters, I'd suggest an explicit x = set() instead.

    "Explicit is better than implicit."

    0 讨论(0)
  • 2021-01-03 23:41

    As has been pointed out - the way to get an empy set literal is via set(), however, if you re-wrote your code, you don't need to worry about this, eg (and using set()):

    from operator import itemgetter
    query = ['four', 'two', 'three']
    result = set().union(*itemgetter(*query)(inversIndex))
    # set([0, 1, 2])
    
    0 讨论(0)
  • 2021-01-03 23:43

    You can just construct a set:

    >>> s = set()
    

    will do the job.

    0 讨论(0)
  • 2021-01-03 23:47

    The "proper" way to do it:

    myset = set()
    

    The {...} notation cannot be used to initialize an empty set

    0 讨论(0)
提交回复
热议问题