Python:检查'Dictionary'是否为空似乎不起作用 [英] Python: Checking if a 'Dictionary' is empty doesn't seem to work
本文介绍了Python:检查'Dictionary'是否为空似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检查一个字典是否为空,但是它的行为不正常。它只是跳过它,并显示在线,除了显示消息之外没有任何东西。任何想法为什么?
I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays ONLINE without anything except of display the message. Any ideas why ?
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()))
推荐答案
空字典评估为 False在Python中
:
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
因此,您的 isEmpty
函数是不必要的。所有你需要做的是:
Thus, your isEmpty
function is unnecessary. All you need to do is:
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()))
这篇关于Python:检查'Dictionary'是否为空似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文