[英]How to check if tuple having a list or dictionary is empty
I have a tuple:我有一个元组:
details = ({}, [])
As there is no data in the following tuple I want to return a null response.由于以下元组中没有数据,我想返回一个空响应。 For this I am writing:
为此,我正在写:
if not details:
return Response({})
else:
print "Not null"
But this does not seem to work as it is always going in the else
part and printing not null.但这似乎不起作用,因为它总是在
else
部分进行并且打印不为空。 I am new to python.我是 python 的新手。 Any help is appreciated.
任何帮助表示赞赏。
Note : if you write:
注意 :如果你写:
if <expr>: pass
then Python will not check that
<expr> == True
, it will evaluate the truthiness of the<expr>
.然后Python 不会检查
<expr> == True
,它会评估<expr>
的真实性 。 Objects have some sort of defined "truthiness" value.对象具有某种定义的“真实性”价值。 The truthiness of
True
andFalse
are respectivelyTrue
andFalse
.True
与False
的真实性分别是True
与False
。 ForNone
, the truthiness isFalse
, for numbers usually the truthiness isTrue
if and only if the number is different from zero, for collections (tuples, sets, dictionaries, lists, etc.), the truthiness isTrue
if the collection contains at least one element.对于
None
,真实性是False
,因为数字通常真实性是True
当且仅当数字不等于0时,对于集合(元组,集合,字典,列表等),如果集合包含at,则真实性为True
至少一个元素。 By default custom classes have alwaysTrue
as truthiness, but by overriding the__bool__
(or__len__
), one can define custom rules.默认情况下,自定义类始终
True
为感实性,但通过重写__bool__
(或__len__
),一个可以自定义规则。
The truthiness of tuple is True
given the tuple itself contains one or more items (and False
otherwise). 元组的真实性是
True
因为元组本身包含一个或多个项目(否则为False
)。 What these elements are, is irrelevant. 这些元素是什么,是无关紧要的。
In case you want to check that at least one of the items of the tuple has truthiness True
, we can use any(..)
: 如果你想检查的元组的项目中的至少一个具有感实性
True
,我们可以用any(..)
if not
any(details
): # all items are empty
return Response({})
else:
print "Not null"
So from the moment the list contains at least one element, or the dictonary, or both, the else
case will fire, otherwise the if
body will fire. 因此,从列表包含至少一个元素或dictonary或两者的那一刻起,
else
情况将会触发,否则if
body将会触发。
If we want to check that all elements in the tuple have truthiness True
, we can use all(..)
: 如果我们想检查元组中的所有元素是否
True
,我们可以使用all(..)
:
if not
all(details
): # one or more items are empty
return Response({})
else:
print "Not null"
The accepted answer implies that any
does not perform a deep search for truth.公认的答案意味着
any
人都不会对真相进行深入的探索。 This is demonstrated below:如下所示:
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.