我正在检查字典是否是空的,但它的行为不正常。它只是跳过它并显示联机而除了显示消息之外没有任何内容。你知道为什么吗?
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()))
如果长度为零,则表示dict为空
Python中的空词典evaluate to ^{} :
因此,您的
isEmpty
函数是不必要的。你需要做的就是:有三种方法可以检查dict是否为空。不过,我更喜欢用第一种方式。另外两种方式太罗嗦了。
相关问题 更多 >
编程相关推荐