Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查嵌套列表是否仅包含空字符串_Python_Python 2.7_Nested Lists - Fatal编程技术网

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

Python 如何检查嵌套列表是否仅包含空字符串,python,python-2.7,nested-lists,Python,Python 2.7,Nested Lists,在pyqt中,我有一个用户可以编辑的qtableview。如果用户对表进行了更改,则在用户完成更改后将复制该表。如果未进行任何更改,则跳过该表。表中填充了空字符串,即: table = [["","",""],["","",""]] 我想检查表是否只包含“,如果包含,则忽略它。如果没有,即包含“1”,则列表中会运行一些代码。 现在我有了一个可以工作的代码,但它不是很像python,我想知道如何改进它。我的代码如下: tabell1 = [["","",""],["","",""]] meh =

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

table = [["","",""],["","",""]]
我想检查表是否只包含
,如果包含,则忽略它。如果没有,即包含
“1”
,则列表中会运行一些代码。 现在我有了一个可以工作的代码,但它不是很像python,我想知道如何改进它。我的代码如下:

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

我看到的最重要的一点可能是使用了空字符串被认为是假的这一事实,类似这样的

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

尽管这意味着任何只包含
[
]
实例的表都将被视为空表。

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

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