Uns*_*ing 337 python dictionary
我正在尝试检查字典是否为空但它的行为不正常.除了显示消息之外,它只是跳过它并显示ONLINE而没有任何内容.有什么想法吗?
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()))
Run Code Online (Sandbox Code Playgroud)
iCo*_*dez 644
空字典在Python中评估False:
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
Run Code Online (Sandbox Code Playgroud)
因此,您的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()))
Run Code Online (Sandbox Code Playgroud)
dou*_*leo 107
以下三种方法可以检查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"
Run Code Online (Sandbox Code Playgroud)
Sha*_*thi 15
检查空字典的简单方法如下:
a= {}
1. if a == {}:
print ('empty dict')
2. if not a:
print ('empty dict')
Run Code Online (Sandbox Code Playgroud)
虽然方法 1 更严格,因为当 a = None 时,方法 1 会提供正确的结果,但方法 2 会给出不正确的结果。
小智 12
dict = {}
print(len(dict.keys()))
Run Code Online (Sandbox Code Playgroud)
如果length为零则表示dict为空
字典可以自动转换为布尔值,False对于空字典和True非空字典,其计算结果为。
if myDictionary: non_empty_clause()
else: empty_clause()
Run Code Online (Sandbox Code Playgroud)
如果这看起来太惯用,您还可以测试len(myDictionary)零或set(myDictionary.keys())空集,或者简单地测试与 的相等性{}。
isEmpty 函数不仅是不必要的,而且您的实现存在多个我可以初步发现的问题。
return False声明缩进一级太深。它应该在 for 循环之外并且与语句处于同一级别for。因此,如果存在某个键,您的代码将仅处理一个任意选择的键。如果键不存在,该函数将返回None,并将其转换为布尔值 False。哎哟! 所有空字典将被归类为假否定。return False语句的缩进并将其移出循环for。然后你得到的是所有键的布尔或False,或者字典是否为空。但仍然会出现误报和误报。根据以下词典进行更正和测试以获取证据。myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
len(given_dic_obj)
Run Code Online (Sandbox Code Playgroud)
如果没有元素则返回 0。否则,返回字典的大小。
bool(given_dic_object)
Run Code Online (Sandbox Code Playgroud)
False如果字典为空则返回,否则返回 True。