Python 创建一个空集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17663299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:50:20  来源:igfitidea点击:

Creating an empty set

python

提问by Chris Degnen

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 found if I populate the set with a dummy value I can use it, but it's not very elegant. Can someone tell me the proper way to do this? Thanks.

我有一些代码可以汇总一组选定的值。我想定义一个空集并添加到它,但{}一直变成字典。我发现如果我用一个虚拟值填充集合,我可以使用它,但它不是很优雅。有人可以告诉我这样做的正确方法吗?谢谢。

inversIndex = {'five': {1}, 'ten': {2}, 'twenty': {3},
               'two': {0, 1, 2}, 'eight': {2}, 'four': {1},
               'six': {1}, 'seven': {1}, 'three': {0, 2},
               'nine': {2}, 'twelve': {2}, 'zero': {0, 1, 3},
               'eleven': {2}, 'one': {0}}

query = ['four', 'two', 'three']

def orSearch(inverseIndex, query):
    b = [ inverseIndex[c] for c in query ]
    x = {'dummy'}
    for y in b:
        { x.add(z) for z in y }
    x.remove('dummy')
    return x

orSearch(inverseIndex, query)

{0, 1, 2}

{0, 1, 2}

采纳答案by Jon Kiparsky

You can just construct a set:

你可以构造一个集合:

>>> s = set()

will do the job.

会做的工作。

回答by inspectorG4dget

The "proper" way to do it:

“正确”的方式来做到这一点:

myset = set()

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

{...}符号不能用于初始化空集

回答by Jon Clements

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

正如已经指出的那样 - 获得 empyset文字的方法是 via set(),但是,如果您重新编写代码,则无需担心这一点,例如(并使用set()):

from operator import itemgetter
query = ['four', 'two', 'three']
result = set().union(*itemgetter(*query)(inversIndex))
# set([0, 1, 2])

回答by pycoder

A set literal is just a tupleof values in curly braces:

集合文字只是花括号中的一组值:

x = {2, 3, 5, 7}

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

因此,您可以使用花括号中的元组创建一个空集:

x = {*()}

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

尽管如此,仅仅因为你可以,并不意味着你应该

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

除非它是一个混淆的编程,或者每个字符都很重要的codegolf,否则我建议使用显式x = set()

"Explicit is better than implicit."

“显式优于隐式。”