[英]How to check if tuple having a list or dictionary is empty
我有一个元组:
details = ({}, [])
由于以下元组中没有数据,我想返回一个空响应。 为此,我正在写:
if not details:
return Response({})
else:
print "Not null"
但这似乎不起作用,因为它总是在else
部分进行并且打印不为空。 我是 python 的新手。 任何帮助表示赞赏。
注意 :如果你写:
if <expr>: pass
然后Python 不会检查
<expr> == True
,它会评估<expr>
的真实性 。 对象具有某种定义的“真实性”价值。True
与False
的真实性分别是True
与False
。 对于None
,真实性是False
,因为数字通常真实性是True
当且仅当数字不等于0时,对于集合(元组,集合,字典,列表等),如果集合包含at,则真实性为True
至少一个元素。 默认情况下,自定义类始终True
为感实性,但通过重写__bool__
(或__len__
),一个可以自定义规则。
元组的真实性是True
因为元组本身包含一个或多个项目(否则为False
)。 这些元素是什么,是无关紧要的。
如果你想检查的元组的项目中的至少一个具有感实性 True
,我们可以用any(..)
if not any(details): # all items are empty
return Response({})
else:
print "Not null"
因此,从列表包含至少一个元素或dictonary或两者的那一刻起, else
情况将会触发,否则if
body将会触发。
如果我们想检查元组中的所有元素是否True
,我们可以使用all(..)
:
if not all(details): # one or more items are empty
return Response({})
else:
print "Not null"
公认的答案意味着any
人都不会对真相进行深入的探索。 如下所示:
not not [] # False (double negation as truthness detector).
not not ([],) # True
not not any(([],)) # False
not not any(([1],)) # True
not not any(([None],)) # Still True, as expected.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.