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

5
我有一个元组:
details = ({}, [])

由于以下元组中没有数据,我想返回一个空响应。为此,我正在编写:
 if not details:
      return Response({})
 else:
    print "Not null"

但是似乎这并不起作用,因为它总是进入else部分并打印出非空。我是Python的新手。任何帮助都将不胜感激。

6
如果details中没有任何元素: - Klaus D.
2个回答

11

Note: if you write:

if <expr>:
    pass

then Python will not check that <expr> == True, it will evaluate the truthiness of the <expr>. Objects have some sort of defined "truthiness" value. The truthiness of True and False are respectively True and False. For None, the truthiness is False, for numbers usually the truthiness is True if and only if the number is different from zero, for collections (tuples, sets, dictionaries, lists, etc.), the truthiness is True if the collection contains at least one element. By default custom classes have always True as truthiness, but by overriding the __bool__ (or __len__), one can define custom rules.

如果元组本身包含一个或多个项目,则元组的真实性为True(否则为False)。这些元素是什么无关紧要。

如果您想检查元组中至少有一个项目的真实性为True,我们可以使用any(..)

if not <b>any(</b>details<b>)</b>:  # all items are empty
    return Response({})
else:
    print "Not null"

因此,从列表中至少包含一个元素或字典(或两者同时包含)的那一刻起,将触发else情况,否则将触发if主体。

如果我们想要检查元组中的所有元素是否都为真值True,可以使用all(..)

if not <b>all(</b>details<b>)</b>:  # one or more items are empty
    return Response({})
else:
    print "Not null"

今天学到了新东西。谢谢。你能解释一下为什么 details == True 返回 False,但是 if details: print('True') 在提示符中打印 True 吗? - MiniGunnR
1
@MiniGunnR:因为 if <expr> 不会检查 <expr> == True,而是评估其真实性 - Willem Van Onsem
2
相当详细的答案 - jamylak
1
谢谢。解释得非常好。 - Sharayu Jadhav

0

被接受的答案暗示了 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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接