Python:检查“Dictionary”是否为空似乎没有

2024-04-19 22:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在检查字典是否是空的,但它的行为不正常。它只是跳过它并显示联机而除了显示消息之外没有任何内容。你知道为什么吗?

 def isEmpty(self, dictionary):
   for element in dictionary:
     if element:
       return True
     return False

 def onMessage(self, socket, message):
  if self.isEmpty(self.users) == False:
     socket.send("Nobody is online, please use REGISTER command" \
                 " in order to register into the server")
  else:
     socket.send("ONLINE " + ' ' .join(self.users.keys())) 

Tags: inselfsendfalse消息dictionaryreturnif
3条回答
dict = {}
print(len(dict.keys()))

如果长度为零,则表示dict为空

Python中的空词典evaluate to ^{}

>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>

因此,您的isEmpty函数是不必要的。你需要做的就是:

def onMessage(self, socket, message):
    if not self.users:
        socket.send("Nobody is online, please use REGISTER command" \
                    " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))

有三种方法可以检查dict是否为空。不过,我更喜欢用第一种方式。另外两种方式太罗嗦了。

test_dict = {}

if not test_dict:
    print "Dict is Empty"


if not bool(test_dict):
    print "Dict is Empty"


if len(test_dict) == 0:
    print "Dict is Empty"

相关问题 更多 >