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

时间:2015-03-15 18:03:03

标签: python set

我有一个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)

1 个答案:

答案 0 :(得分:8)

像所有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