我如何测试 Python 中的 defaultdict(set) 是否为空

How can I test to see if a defaultdict(set) is empty in Python

我有一个 defaultdict fishparts = defaultdict(set),它分配了元素,但使用 .clear() 定期清除我需要的是一些方法来测试集合是否清晰,所以我可以做一些下面函数中的其他工作。

def bandpassUniqReset5(player,x,epochtime):
    score = 0
    if lastplay[player] < (epochtime - 300):
        fishparts[player].clear()
    lastplay[player] = epochtime
    for e in x:
        # right here I want to do a check to see if the "if" conditional above has cleared fishparts[player] before I do the part below
        if e not in fishparts[player]:
            score += 1
        fishparts[player].add(e)
    return str(score)

与所有 Python 容器一样,集合在空时被视为 False:

if not fishparts[player]:
    # this set is empty

参见Truth Value Testing

演示:

>>> if not set(): print "I am empty"
... 
I am empty
>>> if set([1]): print "I am not empty"
... 
I am not empty