25

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

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}

4

4 回答 4

58

你可以构造一个集合:

>>> s = set()

将完成这项工作。

于 2013-07-15T20:29:05.723 回答
8

“正确”的做法:

myset = set()

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

于 2013-07-15T20:29:14.850 回答
4

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

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."

于 2019-10-17T22:35:23.750 回答
3

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

from operator import itemgetter
query = ['four', 'two', 'three']
result = set().union(*itemgetter(*query)(inversIndex))
# set([0, 1, 2])
于 2013-07-15T20:38:45.607 回答