【问题标题】:Python: condition to check that none of list's element is an empty listPython:检查列表元素是否为空列表的条件
【发布时间】:2021-12-09 20:49:01
【问题描述】:

我有一个列表列表A; A 的每个元素都是一个列表。 我想要一个条件(用于 if 语句),如果 A 的所有元素都不为空,则返回 True,否则返回 False。 我该如何表达这个条件?

示例 1

A = [[], [5]]
if (condition):
    print("no empty list as elements of A")
else:
    print("at least an empty list inside A")
>>> at least an empty list inside A

示例 2

A = [[3,2], [5]]
if (condition):
    print("no empty list as elements of A")
else:
    print("at least an empty list inside A")
>>> no empty list as elements of A

我尝试了条件

if(not b for b in A):

但它似乎无法正常工作。我错过了什么?

【问题讨论】:

    标签: python list if-statement boolean-logic boolean-expression


    【解决方案1】:

    由于非空列表被认为是真实的,您可以使用all

    if all(A):
        print("No empty list in A")
    else:
        print("At least one empty list in A")
    

    【讨论】:

    • 谢谢,这正是我想要的!你知道为什么我尝试的解决方案(问题结束)不起作用吗?
    • (not b for b in A) 是一个生成器表达式,它始终为真。你实际上并没有迭代它,如果你这样做了,你会得到一个布尔值列表,而不是一个。
    猜你喜欢
    • 2015-09-15
    • 2017-09-05
    • 2017-09-01
    • 2022-08-16
    • 2012-04-03
    • 2020-06-20
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    相关资源
    最近更新 更多