繁体   English   中英

如何检查具有列表或字典的元组是否为空

[英]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>真实性 对象具有某种定义的“真实性”价值。 TrueFalse的真实性分别是TrueFalse 对于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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM