如何检查嵌套列表是否只包含空字符串

How to check if a nested list contain only empty strings

在 pyqt 中,我有一个用户可以编辑的 qtable视图。如果用户对 table 进行了更改,则 table 将在用户完成后被复制。如果未进行任何更改,则跳过 table。 table 填充了空字符串,即:

table = [["","",""],["","",""]]

我想检查 table 是否仅包含 "",如果包含,则忽略它。如果不存在,即包含 "1",一些代码会在列表中运行。 现在我有一个工作代码,但它不是很 pythonic,我想知道如何改进它。我的代码如下:

tabell1 = [["","",""],["","",""]]
meh = 0
for item in self.tabell1:
    for item1 in item:
        if item1 == "":
            pass
        else:
            meh = 1
if meh == 1:
    do the thing

我看到的可能更 pythonic 的主要事情是使用空字符串被认为是错误的事实,像这样...

tabell1 = [["","",""],["","",""]]
meh = 0
for sublist in self.tabell1:
    if any(sublist):  # true if any element of sublist is not empty
        meh = 1
        break         # no need to keep checking, since we found something
if meh == 1:
    do the thing

或者您可以通过将列表转换为字符串来避免遍历列表,删除所有只有在它为空时才会出现的字符,然后检查它是否为空:

tabell1 = [["","",""],["","",""]]
if not str(tabell1).translate(None, "[]\"\', "):
    #do the thing

尽管这意味着任何仅包含 []"'[=20= 实例的表] 将被视为空。

要检查任何子列表中的任何元素是否满足条件,您可以使用 any 和嵌套生成器表达式:

tabell1 = [["","",""],["","",""]]
if any(item for sublist in tabell1 for item in sublist):
    # do the thing

这样还有一个好处就是一找到一个非空字符串就停止!您的方法将继续搜索,直到它检查了所有子列表中的所有项目。

空字符串被视为 False,每个包含至少一项的字符串被视为 True。但是,您也可以明确地与空字符串进行比较:

tabell1 = [["","",""],["","",""]]
if any(item != "" for sublist in tabell1 for item in sublist):
    # do the thing